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

转载请注明出处:http://blog.csdn.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
****************************************************************/


  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值