题目:
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)将链表分成长度相等的两部分part1和part2;2)将part2翻转一下;3)将part1和翻转后的part2进行顺次合并。我第一次做这道题目的时候没有想到用two pointers,所以线性扫描了好几遍,虽然时间复杂度仍然符合题目要求,但是代码显得冗长。用了two pointers的思路之后,代码就简练多了。
代码:
/**
* 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 || !head->next) {
return;
}
ListNode *slow = head, *fast = head;
ListNode *p = head, *q = head;
while (fast->next && fast->next->next) {
slow = slow->next;
fast = fast->next->next;
}
fast = slow->next; // separate the list
slow->next = NULL;
p = fast, q = fast->next, fast->next = NULL;
while (q) { // reverse the second list
ListNode *temp = q->next;
q->next = p;
p = q;
q = temp;
}
q = head;
while (p && q) {
ListNode *temp1 = q->next, *temp2 = p->next;
p->next = q->next;
q->next = p;
q = temp1, p = temp2;
}
}
};