从头到尾打印链表

题目:输入一个链表的头节点,从尾到头反过来打印出每个节点的值。链表的定义如下:

typedef int DataType;

typedef struct Node
{
    DataType data;
    struct Node *next;
}Node, *pList, *pNode;

【解题思路】(递归)
先递归出后面的节点,在输出节点本身。不足:当链表比较长时,会使函数调用层级比较深而导致函数调用栈溢出。

【代码】

void ReversePrint(pList phead)
{
    if (phead != NULL)
    {
        if (phead->next)
        {
            ReversePrint(phead->next);
        }
        printf("%d   ", phead->data);
    }
}

【程序】

#define _CRT_SECURE_NO_WARNINGS 1
# include <stdio.h>
# include <stdlib.h>
# include <assert.h>

typedef int DataType;

typedef struct Node
{
    DataType data;
    struct Node *next;
}Node, *pList, *pNode;

void InitLinkList(pList *pplist)
{
    assert(pplist);
    *pplist = NULL;
}

void PushBack(pList *pplist, DataType x)
{
    pNode cur = *pplist;
    pNode pnode = NULL;
    assert(pplist);
    pnode = (pNode)malloc(sizeof(Node));
    if (pnode == NULL)
    {
        perror("PushBack::malloc");
        exit(EXIT_FAILURE);
    }
    pnode->data = x;
    pnode->next = NULL;
    if (cur == NULL)
    {
        *pplist = pnode;
    }
    else
    {
        while (cur->next != NULL)
        {
            cur = cur->next;
        }
        cur->next = pnode;
    }
}

void Display(pList plist)
{
    pNode cur = plist;
    while (cur)
    {
        printf("%d-->", cur->data);
        cur = cur->next;
    }
    printf("over\n");
}


void Destroy(pList *pplist)
{
    pNode cur = *pplist;
    assert(pplist);
    while (cur)
    {
        pNode del = cur;
        cur = cur->next;
        free(del);
    }
    *pplist = NULL;
}

void ReversePrint(pList phead)
{
    if (phead != NULL)
    {
        if (phead->next)
        {
            ReversePrint(phead->next);
        }
        printf("%d   ", phead->data);
    }
}

void test1()
{
    pList plist;
    pNode ret = NULL;
    InitLinkList(&plist);
    PushBack(&plist, 1);
    PushBack(&plist, 2);
    PushBack(&plist, 3);
    PushBack(&plist, 4);
    PushBack(&plist, 5);
    PushBack(&plist, 6);
    Display(plist);
    ReversePrint(plist);
    Destroy(&plist);
}

int main()
{
    test1();
    system("pause");
    return 0;
}

运行结果:
这里写图片描述

【附加】(栈方法)
每经过一个节点的时候把节点放到一个栈中,遍历完节点后再从栈顶开始逐个输出节点的值。

【代码】

void ReversePrint(pList phead)
{
    std::stack<pList>nodes;
    pNode pnode = phead;
    while (pnode != NULL)
    {
        nodes.push(pnode);
        pnode = pnode->next;
    }
    while (!nodes.empty())
    {
        pnode = nodes.top();
        printf("%d\t", pnode->data);
        nodes.pop();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值