描述: 输入一个链表,从尾到头打印链表每个节点的值。
最初思路:
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*>的。
时间: 2024-11-05 16:30:58