如何逆序输出一个链表的节点内容

1 改变链表结构

即改变链表的指向,把所有的指向都反过来,再输出。

2 不改变链表结构

每遍历一个节点,就把节点的数据放入一个栈里。先进后出的思想。由此想到递归的思想,使用递归来处理。但递归的方法不是很好,当一个链表很长很长时,函数递归的层次很深,势必会导致栈溢出。这里为了举例我就用递归写,代码会很简单,毕竟上万个节点的链表也不会常有。也没必要存那么长,真有那么长的数据用数组加链表的组合来存会更好。

//输入一个链表的头结点,从尾到头输出
#include <iostream>

using namespace std;

struct node
{
    int m_t;
    struct node *next;
};


void func1()
{
    struct node Top;
    struct node *p = &Top;
    struct node *tmp = p;
    for(int i = 0; i < 10; i++)
    {
        tmp->next = new struct node;
        tmp = tmp->next;
        tmp->m_t = i;
    }
    tmp->next = NULL;
    p = p->next;
    while(p != NULL)
    {
        cout << p->m_t << " ";
        p = p->next;
    }
    cout << endl;

    struct node *p1  = &Top;
    struct node *p2 = p1->next;
    struct node *p3 = p2->next;

    while(p2  != NULL)
    {
        p2->next = p1;
        p1 = p2;
        p2 = p3;
        if(p3 != NULL)
            p3 = p3->next;
    }
    Top.next = NULL;

    while(p1->next != NULL)
    {
        cout << p1->m_t << " ";
        p1 = p1->next;
    }
    cout << endl;

}

void myfunc(struct node *p)
{
    if(p != NULL)
    {
        myfunc(p->next);
        cout<< p->m_t << " ";
    }
}

void func2()
{
    struct node Top;
    struct node *p = &Top;
    struct node *tmp = p;
    for(int i = 0; i < 10; i++)
    {
        tmp->next = new struct node;
        tmp = tmp->next;
        tmp->m_t = i;
    }
    tmp->next = NULL;
    p = p->next;
    myfunc(p);
    cout << endl;
}

int main()
{
    func1();//改变了链表的指向
    func2();//不改变链表的指向 使用递归
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值