问题
https://leetcode.com/problems/reorder-list/
解法
step 1, 将链表分成两份,
step 2, 将后一半链表逆序
step 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)
return;
ListNode* slow = head->next;
ListNode* fast = head->next->next;
while(fast)
{
slow = slow->next;
fast = fast->next;
if (fast) fast = fast->next;
}
ListNode* half = slow;
// reverse half;
ListNode* now = half->next;
half->next = NULL;
while(now)
{
ListNode * next = now->next;
now->next = half;
half = now;
now = next;
}
// combain two;
ListNode Head(0);
now = &Head;
while(half)
{
now->next = head;
now= now->next;
head = head->next;
now->next = half;
half = half ->next;
now = now->next;
}
if (head)
{
now->next = head;
now = now->next;
}
now->next = NULL;
head = Head.next;
}
};