您的位置:首页 > 其它

LeetCode:Reorder List

2014-08-30 17:27 369 查看
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}
.

void reorderList(ListNode *head)
{
if(head == NULL)
return;
stack<ListNode*> st;
ListNode* pNew = head;
ListNode* pSecond = head;

while( pSecond->next != NULL && pSecond -> next ->next != NULL)
{
pNew = pNew -> next;
pSecond = pSecond -> next -> next;
}

pSecond = pNew ->next;
pNew->next = NULL;
while(pSecond != NULL)
{
st.push(pSecond);
pSecond = pSecond->next;
}

pNew = head;
while(head!=NULL && !st.empty())
{

pSecond = head;
head = head->next;

pSecond -> next = st.top();
st.pop();
pSecond -> next -> next = head;
}
head = pNew;
}

分析:
1、将链表一分为二,奇数个节点时,前半节多一个相对好写程序

2、将后一半的节点顺序压入桟中

3、遍历前半部分节点,并分别与栈顶的节点合并

已AC 288ms 时间复杂度为O(n) 空间复杂度为O(n)(用到了栈)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode 遍历 合并