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)(用到了栈)