06. 从尾到头打印链表
生活随笔
收集整理的這篇文章主要介紹了
06. 从尾到头打印链表
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
2020-06-22
1.題目描述
輸入一個鏈表的頭節點,從尾到頭反過來返回每個節點的值(用數組返回)。2.題解
1.放入vector中,然后reverse 2.將鏈表反轉3.代碼
/*** Definition for singly-linked list.* struct ListNode {* int val;* ListNode *next;* ListNode(int x) : val(x), next(NULL) {}* };*/ class Solution { public:vector<int> reversePrint(ListNode* head) {vector<int>tmp;ListNode* p=head;while (p){tmp.push_back(p->val);p=p->next;}reverse(tmp.begin(),tmp.end());return tmp;} }; /*** Definition for singly-linked list.* struct ListNode {* int val;* ListNode *next;* ListNode(int x) : val(x), next(NULL) {}* };*/ class Solution { public:vector<int> reversePrint(ListNode* head) {if (!head) return vector<int>(0);vector<int>tmp;ListNode* pre=head,*p=pre->next,*t;pre->next=NULL;while (p){t=p->next;p->next=pre;pre=p;p=t;}while (pre){tmp.push_back(pre->val);pre=pre->next;}return tmp;} };總結
以上是生活随笔為你收集整理的06. 从尾到头打印链表的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mysql-数据库表优化
- 下一篇: Codeforces Round #31