您的位置:首页 > 其它

LeetCode:Reorder List

2014-05-29 22:21 411 查看
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}
.



解题思路:

用栈将整个链表存储,然后将栈顶元素插入到栈底元素的后面,循环多少次呢?链表



的长度除2即可.



解题代码:

/**
 * 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 *> stk;
        ListNode *tmp = head;
        int cnt = 0 ;
        while(tmp)
        {
            stk.push(tmp);
            tmp = tmp->next;
            ++cnt;
        }
        tmp = head ;
        for(int i = 1 ; i <= cnt / 2 ; ++i)
        {
            ListNode *tmp1 = stk.top();
            stk.pop();
            tmp1->next = tmp->next ;
            tmp->next = tmp1 ;
            tmp = tmp1->next;
        }
        if(head)
            tmp->next = NULL ;
    }
};




注:上述代码的空间复杂度是O(n),不过这题应该可以做到O(1)的空间的,遍历链表从中间分割即可.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: