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}.
class Solution {
public:
void reorderList(ListNode *head) {
if(head == NULL || head -> next == NULL) return;
ListNode *mid = getMid(head);
ListNode *back = reverse(mid -> next);
mid -> next = NULL;
ListNode *cur = new ListNode(-1);
while(head && back){
ListNode *tmpa = head -> next;
head -> next = back;
ListNode *tmpb= back ->next;
back ->next = tmpa;
head = tmpa;
back = tmpb;
}
}
ListNode *getMid(ListNode *head){
ListNode *p = head;
ListNode *q = head;
while(q -> next && q -> next ->next){
p = p -> next;
q = q -> next ->next;
}
return p;
}
ListNode *reverse(ListNode *head){
if(head == NULL)
return NULL;
ListNode* p = head->next;
head->next = NULL;
while(p != NULL){
ListNode* tmp = p;
p = p->next;
tmp->next = head;
head = tmp;
}
return head;
}
};
本文介绍了一种链表重新排列算法,通过获取中间节点、反转后半部分链表并交错连接前半部分与反转后的后半部分,实现链表的特定顺序排列。此过程不修改节点值,直接在原有链表上操作。
364

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



