Leetcode Reorder List 143
2017-01-01 14:32
435 查看
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}.
题目链接
在链表问题中,考虑到“原地“ 意味着在已有链表通过拆分-合并来解决问题
这题目分为三步:
1 . 通过双指针扫描,找到中间节点,分为两部分;
2. 把后半部分进行翻转
3. 把翻转的部分和前半部分链表合并
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}.
题目链接
在链表问题中,考虑到“原地“ 意味着在已有链表通过拆分-合并来解决问题
这题目分为三步:
1 . 通过双指针扫描,找到中间节点,分为两部分;
2. 把后半部分进行翻转
3. 把翻转的部分和前半部分链表合并
/** * 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==NULL) return ; //分为两部分 ListNode *fast=head; ListNode *slow=head; while(1){ fast=fast->next; if(fast==NULL) break; fast=fast->next; if(fast==NULL) break; slow=slow->next; } if(slow==NULL) return; // 后半部分翻转 ListNode *cur=slow; ListNode *pre=slow->next; cur->next=NULL; while(pre!=NULL){ ListNode *temp=pre->next; pre->next=cur; cur=pre; pre=temp; } //合并两个链表 ListNode *first=head; ListNode *second=cur; while(first!=NULL && second!=NULL && first!=second){ ListNode *temp=second->next; second->next=first->next; first->next=second; first=second->next; second=temp; } return ; } };
相关文章推荐
- LeetCode 143 Reorder List Add to List
- leetcode-Reorder List-143
- LeetCode(143) Reorder List
- LeetCode 143 Reorder List (链表 Map或快慢指针 推荐)
- (Leetcode 143 )Reorder List
- [LeetCode]题解(python):143-Reorder List
- 【LEETCODE】143- Reorder List [Python]
- leetcode[143]:Reorder List
- 链表 leetcode 143 Reorder List
- [LeetCode]143 Reorder List
- Reorder List - LeetCode 143
- [leetcode-143]Reorder List(c)
- [Leetcode]#143 Reorder List
- 【leetcode】【单链表】【143】Reorder List
- leetcode 143 —— Reorder List
- leetcode || 143、Reorder List
- leetcode143 Reorder List
- 【leetcode】【单链表】【143】Reorder List
- [Leetcode 143, Medium] Reorder List
- LeetCode143:Reorder List