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

Reorder List [leetcode] 的两种思路

时间:2014-10-08 03:15:24      阅读:277      评论:0      收藏:0      [点我收藏+]

标签:leetcode

第一种思路是用一个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] 的两种思路

标签:leetcode

原文地址:http://blog.csdn.net/peerlessbloom/article/details/39864743

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