Leetcode86. Separated linked list (golang)

1. Topic

Source of the topic: https://leetcode-cn.com/problems/partition-list/

Given a head node of a linked list headand a specific value x, please divide the linked list so that all xnodes less than appear xbefore nodes greater than or equal to .

You should preserve the initial relative position of each node in the two partitions.

  • Example 1:
    insert image description here

Input: head = [1,4,3,2,5,2], x = 3
Output: [1,2,2,4,3,5]

  • Example 2:

Input: head = [2,1], x = 2
Output: [1,2]

  • hint:

The number of nodes in the linked list is in the range [0, 200]
-100 <= Node.val <= 100
-200 <= x <= 200

Two, solution

Solve using two pointers:

  • Here we can create two new linked lists smallhto store xnodes less than and nodes largehgreater than .x
  • smallAt the same time , the pointer is set largeand used to move and add a node that has been judged to be too large in the new linked list.
  • Finally, after headtraversing the linked list, smallconnect the pointer to largeh.Next, splice into a complete linked list, and return smallh.Next.

The diagram is as follows:

insert image description here

  • The time complexity is:
    0 ( n ) 0(n)0(n)
  • The space complexity is:
    0 ( 1 ) 0(1)0(1)

the code

func partition(head *ListNode, x int) *ListNode {
    
    
    small := &ListNode{
    
    }
    large := &ListNode{
    
    }
    smallh := small
    largeh := large
    for head != nil {
    
    
        if head.Val < x {
    
    
            small.Next = head
            small = small.Next
        } else {
    
    
            large.Next = head
            large = large.Next
        }
        head = head.Next
    }
    large.Next = nil
    small.Next = largeh.Next
    return smallh.Next
}

Guess you like

Origin blog.csdn.net/QQ395879676/article/details/115550301