首页 > 代码库 > LeetCode:Reorder List

LeetCode:Reorder List

Given a singly linked listL: 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)的空间的,遍历链表从中间分割即可.