题目:
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 reverseList(ListNode* &head)
{
if(!head || !head->next) return;
ListNode* now = head;
ListNode* pre = NULL;
ListNode* next;
while(now)
{
next = now->next;
now->next = pre;
pre = now;
now = next;
}
head->next = next;
head = pre;
}
void reorderList(ListNode* head) {
if(!head || !head->next || !head->next->next) return;
ListNode* fast = head;
ListNode* slow = head;
while(fast->next != NULL && fast->next->next != NULL)
{
slow = slow ->next;
fast = fast->next -> next;
}
fast = slow->next;
slow->next = NULL;
reverseList(fast);
slow = head;
ListNode* l1;
ListNode* l2;
while(slow && fast)
{
l1 = slow -> next;
l2 = fast ->next;
slow->next = fast;
fast->next = l1;
slow = l1;
fast = l2;
}
return;
}
};
注:调了十几年才搞定。只要问题是,函数调用,如何修改传进去的变量的指向.此外,反转总是会存在一些小细节容易出错,还是得多写写。