从尾到头打印链表

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
/*
* 输入一个链表的头节点,从尾到头反过来打印每个节点的值。
* 且不允许修改输入链表的结构。
*/
 
#include<iostream>
#include<stack>
 
using namespace std;
 
struct ListNode
{
    int m_nKey;
    ListNode* m_pNext;
};
 
/*
解法1:遍历整个链表,将遍历的元素进行压栈,然后再将栈中的数据输出,需要另外再申请O(n)的辅助空间
*/
 
void PrintListReversing_Iteratively(ListNode* pHead)
{
    stack<ListNode*> nodes;
 
    ListNode* pNode = pHead;
    while (pNode != nullptr)
    {
        nodes.push(pNode);
        pNode = pNode->m_pNext;
    }
 
    while (!nodes.empty())
    {
        pNode = nodes.top();
        cout << pNode->m_nKey << " ";
        nodes.pop();
    }
}
 
/*
* 解法2:递归的本质就是一个栈结构,可以利用递归来实现,每次访问一个节点的时候,
* 先递归输出它后面的节点,再输出该节点自身。有一个问题是当链表非常长的时候就会导致
* 函数导致函数调用的层级很深,从而有可能导致函数调用栈溢出。
*/
 
void PrintReversingly(ListNode* pHead)
{
    if (pHead != nullptr)
    {
        if (pHead->m_pNext != nullptr)
        {
            PrintReversingly(pHead->m_pNext);
        }
 
        cout << pHead->m_nKey << " ";
    }
}
 
 
 
int main()
{
    ListNode* node1 = new ListNode();
    ListNode* node2 = new ListNode();
    ListNode* node3 = new ListNode();
    ListNode* node4 = new ListNode();
 
    node1->m_nKey = 1;
    node2->m_nKey = 2;
    node3->m_nKey = 3;
    node4->m_nKey = 4;
 
    node1->m_pNext = node2;
    node2->m_pNext = node3;
    node3->m_pNext = node4;
    node4->m_pNext = nullptr;
 
    PrintListReversing_Iteratively(node1);
    cout << endl;
 
    PrintReversingly(node1);
 
    return 0;
}

  

posted on   xcxfury001  阅读(13)  评论(0编辑  收藏  举报

编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· Ollama——大语言模型本地部署的极速利器
· 使用C#创建一个MCP客户端
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· Windows编程----内核对象竟然如此简单?
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示