Reorder List
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}.
本题 O(n)空间时间做完,但实际有O(1)的做法。
那个办法是把后半部分翻转,然后merge一下就可以了。
/**
* 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) {
stack<ListNode *> sk;
if(head == NULL)return;
int num=1;
ListNode *temp = head;
while(temp ->next != NULL)
{
sk.push(temp->next);
temp =temp->next;
num++;
}
temp = head;
if(num<3)return;
for(int i = 0 ; i < num/2 ;i++)
{
ListNode *last =sk.top();
sk.pop();
if(!sk.empty()){
ListNode *n = sk.top();
n->next =NULL;
}
last->next = temp->next;
temp->next = last;
temp = last->next;
}
}
};
posted on 2014-03-26 16:16 pengyu2003 阅读(114) 评论(0) 收藏 举报
浙公网安备 33010602011771号