单链表的反向输出

问题

有一个带头结点的单链表,编写算法实现从尾到头反向输出每个结点的值

思路一

对于单链表而言只能顺着指针域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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值