从尾到头打印链表
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; }
输出:
相关文章推荐
- 【剑指offer】【从尾到头打印链表 】【栈应用】【注意出栈后size()的变化】
- 链表操作(从尾到头打印链表,使用栈结构实现)
- 输入一个链表,从尾到头打印链表每个节点的值。
- 九度OJ-题目1511:从尾到头打印链表
- 剑指offer面试题——从尾到头打印链表
- 从尾到头打印链表
- [剑指offer]从尾到头打印链表
- 剑指offer之从尾到头打印链表
- 牛客网_剑指offer_从尾到头打印链表
- 从尾到头打印链表
- 剑指offer-从尾到头打印链表-php
- 输入一个链表的头结点,从尾到头反过来打印每个结点的值――5
- (C++)剑指offer-3:从尾到头打印链表
- 【剑指offer】面试题5:从尾到头打印链表
- 剑指offer_面试题5_从尾到头打印链表(栈和递归实现)
- C语言实现: 从尾到头打印链表
- 算法题之二(从尾到头打印链表)
- 剑指Offer---面试题5:从尾到头打印链表
- <笔试><面试>单链表相关(1)从尾到头打印链表、删除一个无头链表的非尾结点
- 剑指offer-从尾到头打印链表