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

Reorder List

时间:2017-03-25 13:06:27      阅读:123      评论:0      收藏:0      [点我收藏+]

标签:部分   null   需要   span   oid   val   init   next   public   

思路:对列表后半部分逆序排列,然后连接。其中还是需要注意head = cur;cur = cur->next;head->next = tmpNode;相对位置。

/**
 * 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) {
        ListNode dummy(-1);
        dummy.next = head;
        
        int count = 0;
        while(head)
        {
            head = head->next;
            ++count;
        }
        
        head = &dummy;
        for(int i=0; i<count/2 + count%2; ++i)
            head = head->next;
        ListNode *tmp = head->next;
        head->next = nullptr;
        
        //reverse the second half
        ListNode *cur = nullptr;
        while(tmp)
        {
            ListNode *tmpNode = tmp->next;
            tmp->next = cur;
            cur = tmp;
            tmp = tmpNode;
        }
        
        for(head = dummy.next; head&&cur;)
        {
            ListNode *tmpNode = head->next;
            head->next = cur;
            head = cur;
            cur = cur->next;
            head->next = tmpNode;
            head = tmpNode;
        }
        head = dummy.next;
    }
};

 

Reorder List

标签:部分   null   需要   span   oid   val   init   next   public   

原文地址:http://www.cnblogs.com/chengyuz/p/6616776.html

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