hihoCoder | 翻转链表

http://hihocoder.com/problemset/problem/1371?sid=983707

描述

翻转一个链表

特殊要求:请使用以下链表结构

class Node
{
    int value;
    Node next;
}

输入

输入包含多组数据。对于每组数据:

第一行是n,表示链表长度;当n=-1时,表示输入结束。(1 <= n <= 100)

第二行是n个整数,表示链表每一位所存储的内容。

输出

针对每组输入,输出翻转后的链表的内容。

样例输入

4
1 3 5 7
-1

样例输出

7 5 3 1

分析

再练习一下链表的基本操作。

C++

#include <iostream>
#include <cstdio>
#include <vector>
#include <queue>

using namespace std;

class ListNode
{
public:
    int val;
    ListNode *next;
    ListNode (int val)
    {
        this->val = val;
        this->next = NULL;
    }
};

int main()
{
    int n;
    while (1) {
        cin >> n;
        if (n == -1) break;
        ListNode dummy(0), *cur = &dummy;

        // construct the linked list
        for (int i = 0; i < n; ++i) {
            int val; cin >> val;
            cur->next = new ListNode(val);
            cur = cur->next;
        }

        // reverse
        ListNode *head = dummy.next;
        ListNode *prev = NULL;
        while (head) {
            ListNode *next = head->next;
            head->next = prev;
            prev = head;
            head = next;
        }
        head = prev;

        // print
        while (head->next) {
            cout << head->val << " ";
            head = head->next;
        }
        cout << head->val << endl;
    }
}

原文地址:https://www.cnblogs.com/ilovezyg/p/6389055.html