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

首頁(yè) > 學(xué)院 > 開發(fā)設(shè)計(jì) > 正文

143. Reorder List(逆序一半再合成)

2019-11-08 02:03:03
字體:
供稿:網(wǎng)友
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}.Subscribe to see which companies asked this question.

第一次代碼:

class Solution {public: void reorderList(ListNode *head) { if(head == NULL || head->next == NULL) return ; ListNode* slow = head; ListNode* fast = head; do{ slow = slow->next; fast = fast->next->next; }while(fast != NULL && fast->next != NULL); //把整個(gè)鏈表劃分成2個(gè)等長(zhǎng)的子鏈表,如果原鏈表長(zhǎng)度為奇數(shù),那么第一個(gè)子鏈表的長(zhǎng)度多1 ListNode* head1 = head; ListNode* head2 = slow->next; slow->next = NULL; ListNode* cur = head2; ListNode* next = cur->next; ListNode* PRev = NULL; while(cur != NULL){ next = cur->next; cur->next = prev; prev = cur; cur = next; } head2 = prev; ListNode* next2 = NULL; while(head2 != NULL){ next = head1->next; next2 = head2->next; head1->next = head2; head2->next = next; head1 = next; head2 = next2; } }};

要注意在中斷點(diǎn)將兩部分都復(fù)制為NULL,否則可能會(huì)輸出太多內(nèi)容。

上面的代碼可讀性甚好,但是申請(qǐng)的變量有點(diǎn)多。下面優(yōu)化了一下,不過到底哪種風(fēng)格好,還是各有千秋吧。

class Solution {public: void reorderList(ListNode* head) { if(head == NULL || head->next == NULL) return ; ListNode* n1 = head; ListNode* n2 = head; do{ n1 = n1->next; n2 = n2->next->next; }while(n2 != NULL && n2->next != NULL); ListNode* n3 = n1->next; n1->next = NULL; n1 = NULL, n2 = n3; while(n2 != NULL){ n3 = n2->next; n2->next = n1; n1 = n2; n2 = n3; } ListNode* n4 = n1; n1 = head, n3 = n4; while(n3 != NULL){ n2 = n1->next; n4 = n3->next; n1->next = n3; n3->next = n2; n1 = n2; n3 = n4; } }};

回過頭來重新做一遍,使用二級(jí)指針+deque:

class Solution {public: void reorderList(ListNode* head) { if(head == NULL) return ; ListNode** pp = &(head->next); ListNode* tmp = head->next; std::deque<ListNode*> deq; while(tmp != NULL){ deq.push_back(tmp); tmp = tmp->next; } bool even = true; while(!deq.empty()){ if(even){ tmp = deq.back(); deq.pop_back(); } else{ tmp = deq.front(); deq.pop_front(); } *pp = tmp; pp = &(tmp->next); tmp->next = NULL; even = !even; } }};
發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 正镶白旗| 孟村| 鄂伦春自治旗| 台安县| 曲靖市| 澄迈县| 息烽县| 江山市| 区。| 莎车县| 大连市| 奈曼旗| 甘德县| 从化市| 九龙坡区| 江华| 清镇市| 宣威市| 勃利县| 靖州| 三河市| 城口县| 调兵山市| 高州市| 文安县| 张家港市| 奎屯市| 甘南县| 沙坪坝区| 黎城县| 徐汇区| 宽城| 哈密市| 清远市| 岢岚县| 蒲江县| 金昌市| 独山县| 昭平县| 姚安县| 太康县|