题目内容:
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. 将未逆序的链表和逆序的后半部分链表各取一个合并起来
代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
// 1. 找到中间节点
// 2. 从中间节点开始到链表尾部,通过任意一种方式(栈、链表翻转等)将节点逆序
// 3. 将未逆序的链表和逆序的后半部分链表各取一个合并起来
void reorderList(ListNode* head) {
if(head == NULL)
return;
ListNode *mid = getMidPoint(head);
ListNode *front = head, *back = mid->next;
stack<ListNode *> backList;
mid->next = NULL;
while(back != NULL) {
backList.push(back);
back = back->next;
}
while(!backList.empty()) {
back = backList.top();
backList.pop();
back->next = front->next;
front->next = back;
front = back->next;
}
}
// return the mid point, if even, return the former one
ListNode *getMidPoint(ListNode* head) {
ListNode *one = head, *two = head->next;
while(two != NULL && two->next != NULL) {
one = one->next;
two = two->next->next;
}
return one;
}
};