刷題6 從尾到頭打印鏈表
阿新 • • 發佈:2017-12-22
gin () pty sta push_back ron 方法 strong val
描述: 輸入一個鏈表,從尾到頭打印鏈表每個節點的值。
最初思路:
1 /** 2 * struct ListNode { 3 * int val; 4 * struct ListNode *next; 5 * ListNode(int x) : 6 * val(x), next(NULL) { 7 * } 8 * }; 9 */ 10 class Solution { 11 public: 12 vector<int> printListFromTailToHead(ListNode* head) {13 vector<int> array; 14 15 while(head != NULL) 16 { 17 array.push_back(head->val); 18 head = head->next; 19 } 20 21 return vector<int>(array.rbegin(), array.rend()); 22 } 23 };
方法多了去了,比如用vector跟stack配合:
1 /** 2 * struct ListNode { 3 * int val; 4 * struct ListNode *next; 5 * ListNode(int x) : 6 * val(x), next(NULL) { 7 * } 8 * }; 9 */ 10 class Solution { 11 public: 12 vector<int> printListFromTailToHead(ListNode* head) { 13 vector<int> result; 14 stack<int> stack; 15 while(head != NULL) 16 { 17 stack.push(head->val); 18 head = head->next; 19 } 20 21 while(!stack.empty()) 22 { 23 result.push_back(stack.top()); 24 stack.pop(); 25 } 26 return result; 27 } 28 };
vector跟stack結合的還有用stack<ListNode*>的。
刷題6 從尾到頭打印鏈表