首页 > 其他 > 详细

143. 重排链表

时间:2020-07-29 01:39:51      阅读:52      评论:0      收藏:0      [点我收藏+]

143. 重排链表

难度中等260给定一个单链表 L:L0→L1→…→Ln-1→Ln ,
将其重新排列后变为: L0→Ln→L1→Ln-1→L2→Ln-2→…
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
示例 1:
给定链表 1->2->3->4, 重新排列为 1->4->2->3.
示例 2:
给定链表 1->2->3->4->5, 重新排列为 1->5->2->4->3.
 

思路:找到中点断开,翻转后面部分,然后合并前后两个链表

 

代码:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    void reorderList(ListNode* head) {
    ListNode *middle, *tail, *right, *left, *t1, *t2;
    if(head && head->next)
    {   
        middle = Find_middle(head);
        tail = middle->next;
        middle->next = NULL;
        right = Reorder(tail);
        left = head;
        while(left&&right)
        {
            t1 = left->next;//t1 = 2 t1 = 3
            t2 = right->next;//t2 = 4 t2 = null
            left->next = right;//1->5 2->4
            left = t1;//left = 2 left = 3
            right->next = left;//5->2 4->3
            right = t2;//right = 4 right = null
        }
    }

        
    }

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

    ListNode *Reorder(ListNode *head)
    {
        //1->2->3->4->5
        ListNode *current, *pre, *temp;
        if(head == NULL||head->next==NULL)
            return head;
        
        current = head;//current = 1
        pre = current->next;//pre = 2
        current->next = NULL;//1->null

        while(pre)
        {
            temp = pre->next; //temp = 4  temp = 5  temp = null
            pre->next = current;// 3->2  4->3  5->4
            current = pre;//current = 3 current = 4 current = 5
            pre = temp;//pre = 4 pre = 5 pre = null
        }
        return current;

    }

};

 

143. 重排链表

原文:https://www.cnblogs.com/jessica216/p/13394329.html

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