问题: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.将两个列表合并
注意点:第一步中前面一半链表最后一个节点的next要置空
第二步中链表逆序之后最后一个节点的next要置空
第三步中前面一半链表的长度小于等于后面一半链表的长度
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reorderList(ListNode *head) {
if(head == NULL || head->next == NULL) return head;
ListNode *QuickNode = head, *SlowNode = head, *tail = NULL;
while(QuickNode != NULL && QuickNode->next != NULL){
tail = SlowNode;
SlowNode = SlowNode->next;
QuickNode = QuickNode->next->next;
}
tail->next = NULL;
reverseList(SlowNode);
ListNode *p = head;
tail = NULL;
while(p != NULL && SlowNode != NULL){
tail = SlowNode;
ListNode *quicktemp = p->next;
ListNode *slowtemp = SlowNode->next;
SlowNode->next = p->next;
p->next = SlowNode;
p = quicktemp;
SlowNode = slowtemp;
}
if (SlowNode != NULL)
tail->next = SlowNode;
return head;
}
void reverseList(ListNode* &head){
if(head == NULL || head->next == NULL) return ;
ListNode *pre = head,*CurrentNode = head->next;
while(CurrentNode != NULL){
ListNode *postNode = CurrentNode->next;
CurrentNode->next = pre;
pre = CurrentNode;
CurrentNode = postNode;
}
head->next = NULL;
head = pre;
}
};