国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

Leetcode 143. Reorder List

2019-11-11 07:47:19
字體:
來源:轉載
供稿:網友

Given a singly linked list L: L0→L1→…→Ln-1→Ln, reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…

You must do this in-place without altering the nodes’ values.

For example, Given {1,2,3,4}, reorder it to {1,4,2,3}.

s思路: 1. 這道題讓把list后半部分reverse后插入前半部分。 2. 做法也是先用快慢指針找到中點,然后把后半部分reverse,最后把reverse的后半部分一個一個的插入到前半部分。問題分成三步,每一步都很獨立,不需要交叉,和前面遇到的幾個步驟交叉進行的問題比,這個就是簡單的問題!

class Solution {public: void reorderList(ListNode* head) { //step 1:找中點! if(!head) return; ListNode* fast=head->next,*slow=head; while(fast&&fast->next){//bug:用fast->next比用fast好 fast=fast->next?fast->next->next:NULL; slow=slow->next; } //step 2: reverse the right half ListNode* pnow=slow->next; while(pnow&&pnow->next){//千年bug:在不知道pnow是否有的情況下,不要直接寫pnow->next,需要加保護 //ListNode* pnext=pnow->next; ListNode* PRe=slow->next; slow->next=pnow->next; pnow->next=pnow->next->next; slow->next->next=pre; } //step 3:merge ListNode* l=head,*r=slow->next; slow->next=NULL;//關鍵位置:把左右兩部分斷開! while(l&&r){ ListNode* p=l->next,*q=r->next; l->next=r; r->next=p; l=p; r=q; } }};
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 禄丰县| 阳原县| 阿拉善左旗| 阳原县| 买车| 昌平区| 伊川县| 泸西县| 龙井市| 隆尧县| 汕尾市| 内乡县| 肇源县| 富蕴县| 淅川县| 长兴县| 天门市| 怀柔区| 安阳县| 湟源县| 化德县| 庆安县| 和龙市| 胶南市| 东源县| 通城县| 东兰县| 托克逊县| 卢龙县| 台北县| 达日县| 张掖市| 永胜县| 即墨市| 屏东市| 平阴县| 定安县| 望谟县| 阳东县| 九江县| 扎兰屯市|