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

143. Reorder List

时间:2017-12-22 21:52:04      阅读:146      评论:0      收藏:0      [点我收藏+]

标签:code   ems   osi   ast   反转   没有   void   tno   ==   

欢迎fork and star:Nowcoder-Repository-github

143. Reorder List

题目:

 Given a singly linked list L: L0→L1→…→Ln-1→Ln,
reorder it to: L0→Ln→L1→Ln-1→L2→Ln-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}. 

解答:

  • 主要思路:快慢指针找到中间节点,将后面的链表反转(前插法),合并链表
  • 注意细节,链表为没有空头结点的
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */

//reorder list
class Solution{
public:

    ListNode* findMiddle(ListNode* head)
    {
        ListNode* slow=head;
        ListNode* fast = head->next;
        while ( fast && fast->next)
        {
            slow = slow->next;
            fast = fast->next->next;
        }
        return slow;
    }

    ListNode* reverse_list(ListNode*head)
    {
        ListNode* pre = head;
        ListNode* temp = head->next;
        ListNode* cur = temp;

        pre->next = NULL;
        
        while (cur)
        {
            temp = cur->next;
            cur->next = pre;

            pre = cur;
            cur = temp;
        }
        return pre;
    }

    void reorderList(ListNode *head) {  //void

        if (head==NULL||head->next==NULL||head->next->next==NULL)
        {
            return;
        }
        //快慢指针找到中间节点,将后面的链表反转(前插法),合并链表
        //另:题目要求是就地解决,应该是不能用辅助栈之类的
        ListNode* middel = findMiddle(head);

        //反转链表
        ListNode* last = reverse_list(middel->next);
        middel->next = NULL;

        ListNode* temp = NULL;
        ListNode* cur = head;
        while (last)  //防止形成环 middel->next = NULL;
        {
            temp = last->next;
            last->next = cur->next;

            cur->next = last;

            last = temp;
            cur = cur->next->next;
        }

        return;
    }
};

题目来源:143. Reorder List

143. Reorder List

标签:code   ems   osi   ast   反转   没有   void   tno   ==   

原文地址:http://www.cnblogs.com/ranjiewen/p/8087490.html

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