1. Topic
Source of the topic: https://leetcode-cn.com/problems/partition-list/
Given a head node of a linked list head
and a specific value x
, please divide the linked list so that all x
nodes less than appear x
before nodes greater than or equal to .
You should preserve the initial relative position of each node in the two partitions.
- Example 1:
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
smallh
to storex
nodes less than and nodeslargeh
greater than .x
small
At the same time , the pointer is setlarge
and used to move and add a node that has been judged to be too large in the new linked list.- Finally, after
head
traversing the linked list,small
connect the pointer tolargeh.Next
, splice into a complete linked list, and returnsmallh.Next
.
The diagram is as follows:
- 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
}