其他分享
首页 > 其他分享> > 链表重排

链表重排

作者:互联网

 

 

 

https://leetcode.cn/problems/reorder-list/solution/zhong-pai-lian-biao-by-leetcode-solution/

/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */

 // 找中点+反转后半部分+合并前后两部分,时间复杂度O(n),空间复杂度O(1)
func reorderList(head *ListNode)  {
    if head==nil || head.Next==nil || head.Next.Next==nil{
        return
    }

    // 1. 找中点,让slow指向中点,或左中点位置
    slow := head; fast := head.Next
    for fast!=nil && fast.Next!=nil {
        slow = slow.Next
        fast = fast.Next.Next
    }

    // 2. 断开中点,反转链表后半部分
    var head2 *ListNode
    next := slow.Next
    slow.Next = nil
    slow = next //slow指向后半部分链表的头结点
    for slow != nil {
        next = slow.Next
        slow.Next = head2
        head2 = slow
        slow = next
    }

    // 3. 合并链表head和head2
    curr := head
    curr2 := head2
    for curr != nil && curr2!=nil {
        next = curr.Next
        curr.Next = curr2
        curr2 = curr2.Next
        curr.Next.Next = next
        curr = next
    }
}

 

 

标签:head,slow,curr,nil,Next,链表,重排,next
来源: https://www.cnblogs.com/-citywall123/p/16469614.html