【题目描述】
输入一个链表,从尾到头打印链表每个节点的值。
输入描述:
输入为链表的表头
输出描述:
输出为需要打印的“新链表”的表头
【代码实现】
实现一:基于栈的实现
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(struct ListNode* head) { 13 stack <struct ListNode*> nodes; 14 struct ListNode* pNode=head; 15 vector <int> vec; 16 while(pNode!=NULL) 17 { 18 nodes.push(pNode); 19 pNode=pNode->next; 20 } 21 22 while(!nodes.empty()) 23 { 24 vec.push_back(nodes.top()->val); 25 nodes.pop(); 26 } 27 return vec; 28 } 29 };
实现二:利用vector的插入函数
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(struct ListNode* head) { 13 struct ListNode* pNode=head; 14 vector <int> vec; 15 while(pNode!=NULL) 16 { 17 vec.insert(vec.begin(),pNode->val); 18 pNode=pNode->next; 19 } 20 return vec; 21 } 22 };
【点评】
头插vector 效率太低,可以考虑替代方案:先vector.push_back 返回之前翻转vector,std::reverse(begin,end)。
实现三:利用vector的反转函数
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(struct ListNode* head) { 13 struct ListNode* pNode=head; 14 vector <int> vec; 15 while(pNode!=NULL) 16 { 17 vec.push_back(pNode->val); 18 pNode=pNode->next; 19 } 20 reverse(vec.begin(),vec.end()); 21 return vec; 22 } 23 };