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}.
/**
* 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 ;
}
ListNode *prev = NULL;
ListNode *slow = head;
ListNode *fast = head;
while (fast && fast->next) {
prev = slow;
slow = slow->next;
fast = fast->next->next;
}
prev->next = NULL;
slow = reverse(slow);
ListNode *curr = head;
while (curr->next) {
ListNode *tmp = curr->next;
curr->next = slow;
slow = slow->next;
curr->next->next = tmp;
curr = tmp;
}
curr->next = slow;
}
ListNode *reverse(ListNode *head) {
if (!head || !head->next) {
return head;
}
ListNode *prev = head;
for (ListNode *cur = head->next, *next = cur->next; cur; prev = cur, cur = next, next = cur?cur->next:NULL) {
cur->next = prev;
}
head->next = NULL;
return prev;
}
};
本文介绍了一种链表重组算法,该算法将给定的单链表重新排列为特定的交错形式,即首尾元素相邻,随后是次首次尾元素相邻,以此类推。文章详细解释了如何通过双指针技巧找到链表中点,再反转后半部分链表,并交织合并前半部分和反转后的后半部分链表。
364

被折叠的 条评论
为什么被折叠?



