-
题目描述:
-
输入一个链表,反转链表后,输出链表的所有元素。
(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【解题思路】本题正确思路应该是应三个指针p1,p2,p3分别指向相邻的三个元素a,b,c,然后p2->next=p1,p1=p2,p2=p3,p3=p3->next,然后就是继续调整。同时注意对NULL的处理。
但我采用了stl中的list数据结构和其本身具有的reverse函数来完成,因为觉得这种题目要做也可以。
AC code:
#include <cstdio>
#include <list>
using namespace std;
int main()
{
int n;
while(scanf("%d",&n)!=EOF)
{
if(n!=0)
{
list<int> lst;
int tt;
for(int i=0;i<n;++i)
{
scanf("%d",&tt);
lst.push_back(tt);
}
lst.reverse();
for(list<int>::iterator it=lst.begin();it!=lst.end();++it)
{
if(it!=lst.begin())
printf(" ");
printf("%d",*it);
}
printf("\n");
}else
printf("NULL\n");
}
return 0;
}
/**************************************************************
Problem: 1518
User: huo_yao
Language: C++
Result: Accepted
Time:150 ms
Memory:1024 kb
****************************************************************/
题目链接:http://ac.jobdu.com/problem.php?pid=1518
九度-剑指Offer习题全套答案下载:http://download.csdn.net/detail/huoyaotl123/8276299