您的位置:首页 > 其它

从尾到头打印链表

2017-03-02 13:26 363 查看
问题:

输入一个链表的头结点,从尾到头打印出每个结点的值。

解题思路:

典型的后进先出的问题。可以利用栈来实现。从头开始,每遍历一个节点,将其压入栈中,直到遍历之后,从栈顶依次输出每个结点。

#include <stack>
#include <stdio.h>
#include <stdlib.h>
struct ListNode
{
int       m_nValue;
ListNode* m_pNext;
};
ListNode* CreateListNode(int value)
{
ListNode* pNode=new ListNode();
pNode->m_nValue=value;
pNode->m_pNext=nullptr;
return pNode;
}
void ConnectListNodes(ListNode* pCurrent, ListNode* pNext)
{
if(pCurrent == nullptr)
{
printf("Error to connect two nodes.\n");
exit(1);
}
pCurrent->m_pNext=pNext;
}
void PrintList(ListNode* pHead)
{
printf("PrintList starts.\n");

ListNode* pNode = pHead;
while(pNode != nullptr)
{
printf("%d\t", pNode->m_nValue);
pNode = pNode->m_pNext;
}

printf("\nPrintList ends.\n");
}
void DestroyList(ListNode* pHead)
{
ListNode* pNode = pHead;
while(pNode != nullptr)
{
pHead = pHead->m_pNext;
delete pNode;
pNode = pHead;
}
}
void PrintListReversingly_Iteratively(ListNode* pHead)
{
std::stack<ListNode*> nodes;

ListNode* pNode = pHead;
while(pNode != nullptr)
{
nodes.push(pNode);
pNode = pNode->m_pNext;
}

while(!nodes.empty())
{
pNode = nodes.top();
printf("%d\t", pNode->m_nValue);
nodes.pop();
}
}
int main()
{
ListNode* pNode1 = CreateListNode(1);
ListNode* pNode2 = CreateListNode(2);
ListNode* pNode3 = CreateListNode(3);
ListNode* pNode4 = CreateListNode(4);
ListNode* pNode5 = CreateListNode(5);

ConnectListNodes(pNode1, pNode2);
ConnectListNodes(pNode2, pNode3);
ConnectListNodes(pNode3, pNode4);
ConnectListNodes(pNode4, pNode5);

PrintList(pNode1);
PrintListReversingly_Iteratively(pNode1);
printf("\n");
DestroyList(pNode1);
return 0;
}


输出:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  链表 遍历