从尾到头输出链表

1. 将链表逆序,然后从头到尾输出,需要额外操作;

2. 顺序遍历过程中节点进栈,然后输出栈即可,需要额外的栈;

3. 由栈转到递归。

 

#include <iostream>
using namespace std;

typedef struct LNode{
	int data;
	LNode* next;
}*List;

void InsertList(List &l, int data)
{
	LNode *p=new LNode;
	p->data=data;
	if(NULL==l)
		p->next=NULL;
	else
		p->next=l;
	l=p;
}

void Print(List l)//从头到尾
{
	LNode *p=l;
	while(p)
	{
		cout<<p->data<<" ";
		p=p->next;
	}
}

void ReversePrintList(List l)//从尾到头
{
	if(l)
	{
		if(l->next)
			ReversePrintList(l->next);
		cout<<l->data<<" ";

	}
}



void main()
{
	List l=NULL;
	InsertList(l, 23);
	InsertList(l, 43);
	InsertList(l, 11);
	InsertList(l, 74);
	InsertList(l, 69);
	InsertList(l, 52);
	InsertList(l, 73);
	InsertList(l, 66);

	cout<<"从头到尾:";
	Print(l);
	cout<<endl;
	cout<<"从尾到头:";
	ReversePrintList(l);
	cout<<endl;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值