题目来源:http://ac.jobdu.com/problem.php?pid=1518
-
题目描述:
-
输入一个链表,反转链表后,输出链表的所有元素。
(hint : 请务必使用链表)
-
输入:
-
输入可能包含多个测试样例,输入以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>
#include <cstdio>
#include <cstring>
using namespace std;
struct Node
{
int iData;
Node* pNext;
Node()
{
iData = 0;
pNext = NULL;
}
};
Node* pHead;
void Reverse_List()
{
Node* p1 = pHead->pNext;
Node* p2 = p1->pNext;
p1->pNext = NULL;
while(p2 != NULL)
{
Node* tmp = p2->pNext;
p2->pNext = p1;
p1 = p2;
p2 = tmp;
}
pHead->pNext = p1;
}
void Print_List()
{
Node* p1 = pHead->pNext;
while(p1->pNext != NULL)
{
printf("%d ", p1->iData);
p1 = p1->pNext;
}
printf("%d\n", p1->iData);
}
void Delete_List()
{
Node* p1 = pHead;
Node* p2 = NULL;
while(p1 != NULL)
{
p2 = p1->pNext;
delete p1;
p1 = p2;
}
}
int main()
{
int n, i;
while(~scanf("%d", &n))
{
pHead = new Node();
Node* p1 = pHead;
Node* pNode = NULL;
for(i = 0; i < n; ++i)
{
pNode = new Node();
scanf("%d", &pNode->iData);
p1->pNext = pNode;
p1 = pNode;
}
if(pHead->pNext == NULL)
printf("NULL\n");
else if(n == 1)
printf("%d\n", pHead->pNext->iData);
else
{
Reverse_List();
Print_List();
}
Delete_List();
}
return 0;
}