problem:
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}
.
Hide Tags
题意:对单链表重新排序,依次将尾节点插入到头节点的后面。
thinking:
(1)由于单链表只有一个next指针,所以需要借助stack存储节点指针。
(2)每次将stack的顶部节点插入到单链表的头结点的后面,修改相关指针,头指针往后遍历
(3)直到头指针等于stack顶部元素(单链表节点总素为奇数)或者,头指针的下一个节点为stack的顶部元素(总素为偶数),停止遍历
,将最后一个节点next指针置空
code:时间复杂度O(n)
class Solution { public: void reorderList(ListNode* head) { stack<ListNode *> _stack; ListNode *tmp=head; while(tmp!=NULL) { _stack.push(tmp); tmp=tmp->next; } if(_stack.size()<3) return; ListNode *p= head; ListNode *q=_stack.top(); while(p!=q && p->next!=q) { _stack.pop(); ListNode *p_next=p->next; p->next=q; q->next=p_next; p=p_next; q=_stack.top(); } q->next=NULL; } };
时间: 2024-08-02 12:06:01