0
点赞
收藏
分享

微信扫一扫

【2023王道数据结构】【线性表—page40—03】C、C++完整实现(可直接运行)

题目:
在这里插入图片描述
设L为带头节点的单链表,编写算法实现从尾到头反向输出每个节点的值。

解题思路:

>利用递归栈进行实现
>栈的特性是后进先出
>所以可以采用递归实现

代码实现:

#include <iostream>
using namespace std;

typedef struct LNode
{
    int data;
    struct LNode *next;
} LNode, *LinkList;

// 头插法
void HeadInsert(LinkList &L)
{
    int val = 0;
    while (cin >> val)
    {
        LNode *s = new LNode;
        s->data = val;
        s->next = L->next;
        L->next = s;

        if (cin.get() == '\n')
        {
            break;
        }
    }
}

// 尾插法
void TailInsert(LinkList &L)
{
    int val = 0;
    LNode *r = L;
    while (cin >> val)
    {
        LNode *s = new LNode;
        s->data = val;
        r->next = s;
        r = s;
        r->next = NULL;

        if (cin.get() == '\n')
        {
            break;
        }
    }
}

// 遍历输出链表元素
void Print(LinkList L)
{
    LNode *p = L->next;
    while (p)
    {
        cout << p->data << '\t';
        p = p->next;
    }
    cout << endl;
}

void ReversePrint(LinkList &L)
{
    if (L == NULL)
    {
        return;
    }
    ReversePrint(L->next);
    cout << L->data << '\t';
}

int main()
{
    LinkList L = new LNode;
    TailInsert(L);

    ReversePrint(L->next);
}
举报

相关推荐

0 条评论