转载请注明出处:http://blog.csdn.net/ns_code/article/details/25028525
剑指offer上的第五题,在九度OJ上测试通过。
-
题目描述:
-
输入一个链表,从尾到头打印链表每个节点的值。
-
输入:
-
每个输入文件仅包含一组测试样例。
每一组测试案例包含多行,每行一个大于0的整数,代表一个链表的节点。第一行是链表第一个节点的值,依次类推。当输入到-1时代表链表输入完毕。-1本身不属于链表。
-
输出:
-
对应每个测试案例,以从尾到头的顺序输出链表每个节点的值,每个值占一行。
-
样例输入:
-
1 2 3 4 5 -1
-
样例输出:
-
5 4 3 2 1
AC代码如下:
#include<stdio.h>
#include<stdlib.h>
typedef int ElemType;
typedef struct Node
{
ElemType data;
struct Node *next;
}Node,*pNode;
/*
递归从尾到头打印单链表
*/
void PrintListReverse(pNode pHead)
{
if(pHead == NULL)
return;
if(pHead->next != NULL)
PrintListReverse(pHead->next);
printf("%d\n",pHead->data);
}
pNode CreateList()
{
ElemType val;
pNode pHead = NULL;
pNode pCur = NULL;
do
{
scanf("%d",&val);
if(val != -1)
{
pNode pNew = (pNode)malloc(sizeof(Node));
if(pNew == NULL)
exit(EXIT_FAILURE);
pNew->data = val;
pNew->next = NULL;
if(pHead == NULL)
{
pHead = pNew;
pCur = pHead;
}
else
{
pCur->next = pNew;
pCur = pCur->next;
}
}
}while(val != -1);
return pHead;
}
void DestroyList(pNode pHead)
{
if(pHead == NULL)
return;
pNode p = NULL;
while(pHead != NULL)
{
p = pHead->next;
free(pHead);
pHead = p;
}
}
int main()
{
pNode pHead = CreateList();
PrintListReverse(pHead);
DestroyList(pHead);
return 0;
}
/**************************************************************
Problem: 1511
User: mmc_maodun
Language: C
Result: Accepted
Time:100 ms
Memory:5440 kb
****************************************************************/