题目地址
https://leetcode-cn.com/problems/partition-list/
题目描述
给定一个链表和一个特定值 x,对链表进行分隔,使得所有小于 x 的节点都在大于或等于 x 的节点之前。
你应当保留两个分区中每个节点的初始相对位置。
示例:
输入: head = 1->4->3->2->5->2, x = 3
输出: 1->2->2->4->3->5
题解
/**
* 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 smallHead = new ListNode();
ListNode largeHead = new ListNode();
ListNode smallTail = smallHead;
ListNode largeTail = largeHead;
while (head != null) {
if (head.val >= x) {
// head 的值大于等于 x,追加到 large 链表
largeTail.next = head;
largeTail = largeTail.next;
} else {
// head 的值小于 x,追加到 small 链表
smallTail.next = head;
smallTail = smallTail.next;
}
head = head.next;
}
// 合并两个链表
smallTail.next = largeHead.next;
largeTail.next = null;
return smallHead.next;
}
}
网友评论