题目描述
输入链表的第一个节点,从尾到头反过来打印出每个结点的值。
解题思路
- 新建简单的链表用以测试
- 会遍历正确顺序的链表数据
- 不同的方法实现:
- 利用栈
#include <iostream> #include <vector> #include <stack> #include <string> using namespace std; //带头节点的链表 typedef struct ListNode { int m_element; ListNode* m_pNextNode; } *List, *Node; bool isFind(List L, int num) { List pList = L->m_pNextNode; while (pList != nullptr) { if (pList->m_element == num) return true; pList = pList->m_pNextNode; } return false; } List CreatList() { ListNode *pHead = new ListNode; pHead->m_element = -999; pHead->m_pNextNode = nullptr; List pCurPreList = pHead;//待插入节点的前一节点 int num; cout << "Input data(-999 to quit) to creat list:" << endl; while (1) { cin >> num; if(num == -999) break; else { if (!isFind(pHead, num)) { Node newNode = new ListNode; newNode->m_pNextNode = nullptr; newNode->m_element = num; pCurPreList->m_pNextNode = newNode; pCurPreList = newNode;//更新 } } } return pHead; } class Solution { public: vector<int> printListFromTailToHead(ListNode* head) { stack<int> st; vector<int> out; List pList = head->m_pNextNode; while (pList != nullptr) { st.push(pList->m_element); pList = pList->m_pNextNode; } while (!st.empty()) { out.push_back(st.top()); st.pop(); } return out; } }; int main() { Solution sol; List L = CreatList(); vector<int> reverse; reverse = sol.printListFromTailToHead(L); for (int i = 0; i < reverse.size(); i++) { cout << reverse[i] << " "; } cout << endl; system("pause"); return 0; }
- 利用栈