问题
有一个带头结点的单链表,编写算法实现从尾到头反向输出每个结点的值
思路一
对于单链表而言只能顺着指针域next顺序往下搜索,所以我的第一个思路是先顺序遍历一遍将所有的数据保存在一个数组中,并记录链表的长度,之后反向输出数组就可以了,或者保存在一个栈中也可以。后来觉得这种方法有点low,于是有了第二种思路。这种算法没什么好写的,就不写了。
思路二
既然可以用栈,那么可以用递归的方法实现,而且更有助于理解。每当访问一个结点时先递归输出它后面的结点,再输出该结点自身,这样链表就反向输出了。
算法测试如下
#include <stdio.h>
#include <iostream>
using namespace std;
struct node{
int data;
node *next;
node(int x=0)
{
data=x;
next=NULL;
}
};
class List{
public:
node *head;
List()
{
head=new node();
}
void create()//创建链表
{
//cout<<"输入结点的个数";
int n;
cin>>n;
//cout<<"依次输入各结点的值"<<endl;
node *p=head;
for(int i=0;i<n;i++)
{
int x;
cin>>x;
node *newnode=new node(x);
p->next=newnode;
p=p->next;
//cout<<x<<endl;
}
}
void xprint()
{
node *p=head;
while(p->next!=NULL)
{
cout<<p->next->data<<endl;
p=p->next;
}
}
void Print(node *L)
{
//从尾到头输出单链表中的每个结点的值
if(L->next!=NULL)
{
Print(L->next);
}
cout<<"L="<<L<<endl;
cout<<L->data<<endl;
}
};
int main()
{
freopen("in.txt","r",stdin);
List list;
list.create();
//list.xprint();
list.Print(list.head->next);
return 0;
}