- Reorder List
中文English
Given a singly linked list L: L0 → L1 → … → Ln-1 → Ln
reorder it to: L0 → Ln → L1 → Ln-1 → L2 → Ln-2 → …
Example
Example 1:
Input: 1->2->3->4->null
Output: 1->4->2->3->null
Example 2:
Input: 1->2->3->4->5->null
Output: 1->5->2->4->3->null
Challenge
Can you do this in-place without altering the nodes’ values?
解法1:先找到链表中点,然后把右半边链表反转,然后挨个插入左半边链表中。
代码如下:
/**
* Definition of singly-linked-list:
* class ListNode {
* public:
* int val;
* ListNode *next;
* ListNode(int val) {
* this->val = val;
* this->next = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param head: The head of linked list.
* @return: nothing
*/
void reorderList(ListNode * head) {
if (!head || !head->next) return;
ListNode * mid = findMiddle(head);
ListNode * rightHead = reverseList(mid->next);
mid->next = NULL;
ListNode * p = head, * pRight = rightHead;
while(p && pRight) {
ListNode * pNext = p->next;
ListNode * pRightNext = pRight->next;
p->next = pRight;
pRight->next = pNext;
p = pNext;
pRight = pRightNext;
}
return;
}
private:
ListNode * findMiddle(ListNode * head) {
ListNode * slow = head, * fast = head->next;
while(fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
}
return slow;
}
ListNode * reverseList(ListNode * head) {
ListNode * pre = NULL;
while(head) {
ListNode * tmpNode = head->next;
head->next = pre;
pre = head;
head = tmpNode;
}
return pre;
}
};
解法2:用stack。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
void reorderList(ListNode* head) {
stack<ListNode *> stk;
ListNode *node = head;
while (node) {
stk.push(node);
node = node->next;
}
node = head;
while (!stk.empty()) {
ListNode *topNode = stk.top();
stk.pop();
if (node == topNode) {
node->next = NULL;
break;
}
if (node && node->next == topNode) {
topNode->next = NULL;
break;
}
topNode->next = node->next;
node->next = topNode;
node = topNode->next;
}
return;
}
};