国产探花免费观看_亚洲丰满少妇自慰呻吟_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ā)表
主站蜘蛛池模板: 崇信县| 隆尧县| 海南省| 兴安盟| 若尔盖县| 杭州市| 双辽市| 敦化市| 中方县| 远安县| 肥乡县| 绍兴县| 中江县| 大石桥市| 浪卡子县| 天长市| 沁阳市| 邵阳市| 沙雅县| 府谷县| 义马市| 慈溪市| 巴里| 锡林浩特市| 黑山县| 贵州省| 宁阳县| 庆安县| 罗城| 洛扎县| 泸溪县| 额济纳旗| 门头沟区| 确山县| 尼勒克县| 奉贤区| 土默特右旗| 封丘县| 阿城市| 太谷县| 林口县|