分隔链表
描述
中等
给定一个链表和一个特定值 x,对链表进行分隔,使得所有小于 x 的节点都在大于或等于 x 的节点之前。
你应当保留两个分区中每个节点的初始相对位置。
示例
输入: head = 1->4->3->2->5->2, x = 3
输出: 1->2->2->4->3->5
解题
另外定义两个链表,一条放小于x的,一条放大于等于x的
最后两条接起来
# python
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def partition(self, head: ListNode, x: int) -> ListNode:
head_big = ListNode(-1)
head_small = ListNode(-1)
p_big = head_big
p_small = head_small
while head:
if head.val >= x:
p_big.next = head
p_big = p_big.next
else:
p_small.next = head
p_small = p_small.next
head = head.next
p_small.next = head_big.next
p_big.next = None
return head_small.next
// java
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode partition(ListNode head, int x) {
ListNode head_big = new ListNode();
ListNode head_small = new ListNode();
ListNode p_big = head_big;
ListNode p_small = head_small;
while (head != null) {
if (head.val >= x) {
p_big.next = head;
p_big = p_big.next;
} else {
p_small.next = head;
p_small = p_small.next;
}
head = head.next;
}
p_small.next = head_big.next;
p_big.next = null;
return head_small.next;
}
}