标签:
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. 定位到单链表的中间结点mid,并将mid->next置为空
2. 将mid之后的子链表反转
3. 将mid之前的子链表与反转后的子链表归并,顺序是一前一后。
只需要注意边界值情况即可。
下面贴上代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* getMid(ListNode* head){
if (!head)
return NULL;
ListNode* slow = head;
ListNode* fast = head;
while (fast&&fast->next){
fast = fast->next->next;
slow = slow->next;
}
return slow;
}
ListNode* getReversed(ListNode* head){
ListNode* first = new ListNode(0);
ListNode* p = head;
while (p){
ListNode* r = p->next;
p->next = first->next;
first->next = p;
p = r;
}
return first->next;
}
void reorderList(ListNode *head) {
if (!head)
return;
ListNode* mid = getMid(head);
ListNode* midPost = mid->next;
mid->next = NULL;
midPost = getReversed(midPost);
ListNode* first = head;
ListNode* ans = new ListNode(0);
ListNode* r = ans;
ListNode *p, *q;
while (first&&midPost){
p = first->next;
q = midPost->next;
first->next = midPost;
r->next = first;
r = midPost;
first = p;
midPost = q;
}
r->next = p;
}
};
标签:
原文地址:http://blog.csdn.net/kaitankedemao/article/details/44352707