[LeetCode]97. Reorder List链表重排序
2015-12-04 10:10
225 查看
原文链接:https://www.geek-share.com/detail/2660195001.html
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
解法:仔细分析题目意思,一个简单的方法就是将后半部分链表先逆转,然后插入到前半部分。因此可以写出如下代码:/** * 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 || head->next == NULL) return; ListNode *slow = head, *fast = head; while(fast->next != NULL && fast->next->next != NULL) { slow = slow->next; fast = fast->next->next; } ListNode* head1 = head; ListNode* head2 = slow->next; head2 = reverseList(head2); slow->next = NULL; while(head2 != NULL) { ListNode *next1 = head1->next, *next2 = head2->next; head1->next = head2; head2->next = next1; head1 = next1; head2 = next2; } } private: ListNode* reverseList(ListNode* head) { ListNode* rHead = NULL; ListNode* curr = head; ListNode* pTail = NULL; while(curr != NULL) { ListNode* pNext = curr->next; if(pNext == NULL) rHead = curr; curr->next = pTail; pTail = curr; curr = pNext; } return rHead; } };
转载于:https://www.cnblogs.com/aprilcheny/p/5018498.html
相关文章推荐
- [LeetCode] Insertion Sort List 单向链表插入排序
- LeetCode147_Insertion Sort List(用插入排序算法对链表进行排序) Java题解
- leetcode刷题6:对单链表重新排序--reorder list
- LeetCode 148. Sort List--O(nlogn)时间复杂度和常数空间复杂度给链表排序
- LeetCode Sort List 链表排序(规定 O(nlogn) )
- LeetCode 148. Sort List(链表排序)
- LeetCode-Sort List-链表排序-归并排序+链表调整
- [LeetCode] Reorder List 链表重排序
- LeetCode | Insertion Sort List(插入法排序链表)
- leetcode 147. Insertion Sort List-链表插入排序
- LeetCode-Sort List 链表排序
- [LeetCode_83] Remove Duplicates from Sorted List_删除排序链表中的重复元素
- LeetCode-147. Insertion Sort List (JAVA)链表插入排序
- leetcode解题之148. Sort List Java版(对链表排序)
- LeetCode——reorder-list(链表重排序)
- LeetCode 148. Sort List 单链表排序 Python Solution
- [LeetCode] Sort List 链表排序
- [LeetCode] Insertion Sort List 链表插入排序
- LeetCode 21 Merge Two Sorted Lists(合并两个已排序的链表)(Linked List)
- Sort List 链表排序@LeetCode