题目描述
- 输入一个链表,从尾到头打印链表每个节点的值。
算法分析
- 借助堆栈的“后进先出”实现;
- 使用反向迭代器(抖机灵,未贴出代码);
提交代码:
class Solution { public: vector<int> printListFromTailToHead(ListNode* head) { stack<int> stackResult; vector<int> result; if (!head) return result; ListNode* nextNode = head; while (nextNode) { stackResult.push(nextNode->val); nextNode = nextNode->next; } while (!stackResult.empty()) { result.push_back(stackResult.top()); stackResult.pop(); } return result; } };
测试代码:
#include<iostream> #include<vector> #include<stack> #include "ListNode.h" using namespace std; /* // 面试题6:从尾到头打印链表 // 题目:输入一个链表的头结点,从尾到头反过来打印出每个结点的值。 */ // ====================测试代码==================== // 1->2->3->4->5 void Test1() { printf("\nTest1 begins.\n"); 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); Test(pNode1); DestroyList(pNode1); } // 只有一个结点的链表: 1 void Test2() { printf("\nTest2 begins.\n"); ListNode* pNode1 = CreateListNode(1); Test(pNode1); DestroyList(pNode1); } // 空链表 void Test3() { printf("\nTest3 begins.\n"); Test(nullptr); } int main(int argc, char* argv[]) { Test1(); Test2(); Test3(); return 0; }