每天一道LeetCode-----重排链表,节点顺序是从头取一个,从尾取一个,从头取一个,从尾取一个.....
生活随笔
收集整理的這篇文章主要介紹了
每天一道LeetCode-----重排链表,节点顺序是从头取一个,从尾取一个,从头取一个,从尾取一个.....
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Reorder List
原題鏈接Reorder List
要求將鏈表重新排序,有圖片示例可以看到,規則是從頭取一個,再從尾取一個,再從頭取,從尾取,…,這樣進行下去
既然每次都從兩個不同的地方取節點,那么可以將原鏈表從中間拆分成兩個鏈表,一個鏈表是從原鏈表頭到中間節點,另一個鏈表是從原鏈表表尾到中間節點。這樣,只需要從第一個鏈表取一個,再從第二個鏈表取一個,反復進行即可
代碼如下
/*** Definition for singly-linked list.* struct ListNode {* int val;* ListNode *next;* ListNode(int x) : val(x), next(NULL) {}* };*/ class Solution { public:void reorderList(ListNode* head) {if(!head || !head->next)return;auto walker = head;auto runner = head;/* 尋找鏈表中間位置 *//* while(runner && runner->next)和本題的方法在鏈表節點是奇數個時相同* 偶數個時下面的方法會找到中間的左邊,上面的方法會找到中間的右邊 */while(runner && runner->next && runner->next->next){walker = walker->next;runner = runner->next->next;}auto head1 = head;auto head2 = walker->next;walker->next = nullptr;head2 = reverse(head2);while(head1 && head2){auto next1 = head1->next;auto next2 = head2->next;head1->next = head2;head2->next = next1;head1 = next1;head2 = next2;}} private:ListNode* reverse(ListNode* head){ListNode* prev = nullptr;ListNode* cur = head;while(cur){auto next = cur->next;cur->next = prev;prev = cur;cur = next;}return prev;} };總結
以上是生活随笔為你收集整理的每天一道LeetCode-----重排链表,节点顺序是从头取一个,从尾取一个,从头取一个,从尾取一个.....的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 每天一道LeetCode-----将字符
- 下一篇: 每天一道LeetCode-----实现L