题解
解法1:栈
利用栈后进先出的特点,只需要遍历一次链表,然后将栈内元素依次弹出即可。
代码:
class Solution { public: vector<int> printListFromTailToHead(ListNode* head) { stack<int> st; vector<int> ans; if(head == nullptr) return ans; while(head) { st.push(head->val); head = head->next; } while(!st.empty()) { ans.push_back(st.top()); st.pop(); } return ans; } };
解法2:常规做法
遍历一次链表,每个元素直接加入到vector中,然后翻转vector即可
代码:
class Solution { public: vector<int> printListFromTailToHead(ListNode* head) { vector<int> ans; ans.clear(); ListNode* now = head; while(now) { ans.push_back(now->val); now = now->next; } reverse(ans.begin(), ans.end()); return ans; } };
解法3:翻转链表
将链表翻转以后再进行一次遍历即可,翻转链表最简单的做法就是对原链表进行一次头插法遍历
例如1->2->3 将2重新头插得到2->1->3 再将3重新头插得到3->2->1
这种做法会改变原链表,故不在此实现了
最后,三种做法的时间复杂度都是, 空间复杂度都是