輸入可能包含多個測試樣例,輸入以EOF結束。
對於每一個測試案例,輸入的第一行爲一個整數n(0<=n<=1000):表明將要輸入的鏈表的個數。
輸入的第二行包含n個整數t(0<=t<=1000000):表明鏈表元素。 node
對應每一個測試案例,
以此輸出鏈表反轉後的元素,如沒有元素則輸出NULL。 ios
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; }