题目1518:反转链表

输入:

输入可能包含多个测试样例,输入以EOF结束。
对于每个测试案例,输入的第一行为一个整数n(0<=n<=1000):代表将要输入的链表的个数。
输入的第二行包含n个整数t(0<=t<=1000000):代表链表元素。

输出:

对应每个测试案例,
以此输出链表反转后的元素,如没有元素则输出NULL。

样例输入:
5
1 2 3 4 5
0
样例输出:
5 4 3 2 1
NULL
#include <iostream>
using namespace std;
struct Node {
	int data;
	Node* next;

	Node(int data) {
		this->data = data;
		next = NULL;
	}

	Node() {
		this->data = 0;
		next = NULL;
	}
};
int main() {
	int n;
	while (cin >> n) {
		if (n <= 0) {
			cout << "NULL" << endl;
		} else {
			Node* head = new Node;
			cin >> head->data;
			Node* node = NULL;
			Node* p = head;
			for (int i = 1; i < n; i++) {
				node = new Node;
				cin >> node->data;
				p->next = node;
				p = node;
			}

			p = head;
			Node* post = NULL;
			Node* pre = NULL;

			while(p != NULL){
				post = p->next;
				p->next = pre;
				pre = p;
				p = post;

			}

//			p = pre;
			for(int i=0;i<n-1;i++){
				cout<<pre->data<<" ";
				pre = pre->next;
			}
			cout<<pre->data<<endl;
		}
	}
	return 0;
}





你可能感兴趣的:(题目1518:反转链表)