Reorder List
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 == NULL || head->next == NULL || head->next->next == NULL) return;
ListNode *list1 = head, *list2 = head, *headA = head, *headB = head;
//2分成2个表,后面的表逆序
while(list2 != NULL && list2->next != NULL){
list1 = list1->next;
list2 = list2->next->next;
}
headB = list1->next;
list1->next = NULL;
headB = reverse(headB);
//按要求组合
ListNode *p = headA, *q = headB, *now = headB;
while(q){
now = q->next;
q->next = p->next;
p->next = q;
p = p->next->next;
q = now;
}
head = headA;
}
//反转单链表
ListNode* reverse(ListNode *head){
if(head == NULL || head->next == NULL) return head;
ListNode *pre = head,*cur = head->next,*ne = cur->next;
while(ne){
cur->next = pre;
pre = cur;
cur = ne;
ne = ne->next;
}
cur->next = pre;
head->next = NULL;
return cur;
}
};
/**
* 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 || head->next->next == NULL) return;
ListNode *list1 = head, *list2 = head, *headA = head, *headB = head;
//2分成2个表,后面的表逆序
while(list2 != NULL && list2->next != NULL){
list1 = list1->next;
list2 = list2->next->next;
}
headB = list1->next;
list1->next = NULL;
headB = reverse(headB);
//按要求组合
ListNode *p = headA, *q = headB, *now = headB;
while(q){
now = q->next;
q->next = p->next;
p->next = q;
p = p->next->next;
q = now;
}
head = headA;
}
//反转单链表
ListNode* reverse(ListNode *head){
if(head == NULL || head->next == NULL) return head;
ListNode *pre = head,*cur = head->next,*ne = cur->next;
while(ne){
cur->next = pre;
pre = cur;
cur = ne;
ne = ne->next;
}
cur->next = pre;
head->next = NULL;
return cur;
}
};