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
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)(用到了栈)
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 143] Reorder List Solution
- LeetCode解题报告:Reorder List
- [LeetCode] 重排链表 reorder linked list
- LeetCode - Reorder List
- Leetcode -- Reorder List
- [LeetCode]Reorder List
- [leetcode]Reorder List @ Python
- leetcode第143题 ( Reorder List),快慢指针的应用
- LeetCode 143: Reorder List
- LeetCode-Reorder List
- [leetcode] Reorder List
- *LeetCode-Reorder List
- [LeetCode] Reorder List
- leetcode--Reorder List
- leetcode--Reorder List
- Reorder List - Leetcode
- LeetCode-Reorder List
- Reorder List leetcode java
- [leetcode]Reorder List
- 《leetCode》:Reorder List