码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode:Reorder List

时间:2014-06-03 03:12:46      阅读:222      评论:0      收藏:0      [点我收藏+]

标签:leetcode   链表   

Given a singly linked list L: L0L1→…→Ln-1Ln,


reorder it to: L0LnL1Ln-1L2Ln-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)的空间的,遍历链表从中间分割即可.

LeetCode:Reorder List,布布扣,bubuko.com

LeetCode:Reorder List

标签:leetcode   链表   

原文地址:http://blog.csdn.net/dream_you_to_life/article/details/27579905

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!