题目描述
给你一个链表的头节点 head 和一个特定值 x ,请你对链表进行分隔,使得所有 小于 x 的节点都出现在 大于或等于 x 的节点之前。
你应当 保留 两个分区中每个节点的初始相对位置。
样例描述
思路
链表 + 尾插法
- 维护大小两个链表,最后进行拼接。
- 维护过程中注意用尾插法来构建链表,这样方便后面两个链表的拼接。
代码
/**
* 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) {
if (head == null ) return head;
//维护两个链表 小和大
ListNode smallHead = new ListNode(-1);
ListNode small = smallHead;
ListNode largeHead = new ListNode(-1);
ListNode large = largeHead;
ListNode p = head;
//这里给的头结点是带有值的 不能用p.next判断
while (p != null) {
if (p.val < x) {
small.next = p;
small = small.next;
}
else {
large.next = p;
large = large.next;
}
p = p.next;
}
//两个链表进行拼接
small.next = largeHead.next;
large.next = null;
return smallHead.next;
}
}