【剑指offer】打印单列表从尾部到头部

时间:2023-03-10 02:26:33
【剑指offer】打印单列表从尾部到头部

转载请注明出处:http://blog.****.net/ns_code/article/details/25028525


剑指offer上的第五题,在九度OJ上測试通过。

时间限制:1 秒

内存限制:128 兆

题目描写叙述:

输入一个链表。从尾到头打印链表每一个节点的值。

输入:

每一个输入文件仅包括一组測试例子。
每一组測试案例包括多行,每行一个大于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
****************************************************************/

版权声明:本文博主原创文章。博客,未经同意不得转载。