首页 > 其他 > 详细

Reorder List [leetcode] 这两种思路

时间:2015-09-25 23:04:15      阅读:263      评论:0      收藏:0      [点我收藏+]

第一个想法随着vector保存全部Node*

表拼接出来

    void reorderList(ListNode *head) {
        vector<ListNode*> content;
        ListNode * cur = head;
        while (cur)
        {
            content.push_back(cur);
            cur = cur->next;
        }
        int size = content.size();
        cur = NULL;
        for (int i = 0; i <= size - 1 - i; i++)
        {
            if (cur) cur->next = content[i];
            if (i != size - i - 1) content[i]->next = content[size - 1 - i];
            cur = content[size - 1 - i];
        }
        if (cur) cur->next = NULL;
    }

另外一种思路能够分成下面几个步骤:

1. 找到中间的节点nMid

2. 翻转nMid到末尾的链表

3. 拼接head和nMid

代码例如以下

    void reorderList(ListNode *head) {
        if (head == NULL) return;
        ListNode * mid = head;
        ListNode * endOfHead;
        ListNode * end = head;
        while (end)
        {
            end = end->next;
            endOfHead = mid;
            mid = mid->next;
            if (end)  end = end->next;
        }
        endOfHead->next = NULL;//end of first half
        //reverse
        if (mid == NULL) return;
        ListNode* p0, * p1, * p2;
        p1 = mid;
        p2 = mid->next;
		p1->next = NULL;
        while (p2)
        {
            p0 = p1;
            p1 = p2;
            p2 = p2->next;
            p1->next = p0;
        }
        mid = p1;
        //concat
        ListNode * newHead = head;
        while (mid && head)
        {
            head = head->next;
            newHead->next = mid;
            newHead = newHead->next;
            mid = mid->next;
            newHead->next = head;
            newHead = newHead->next;
        }
    }


版权声明:本文博主原创文章。博客,未经同意不得转载。

Reorder List [leetcode] 这两种思路

原文:http://www.cnblogs.com/lcchuguo/p/4839553.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!