题目描述
给定一个链表和一个特定值 x,对链表进行分隔,使得所有小于 x 的节点都在大于或等于 x 的节点之前。
你应当保留两个分区中每个节点的初始相对位置。
示例:
输入: head = 1->4->3->2->5->2, x = 3
输出: 1->2->2->4->3->5
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/partition-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路
整两个空头指针,一个链接val < x的结点,另一个链接val >= x 的结点,最后将两个链表连接起来同时去掉两个空头指针。
关键一步temRight.next = null 可以避免生成循环链表
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode partition(ListNode head, int x) {
ListNode left = new ListNode(-1);
ListNode right = new ListNode(-1);
ListNode temLeft = left,temRight = right;
while(head != null){
if(head.val < x){
temLeft.next = head;
temLeft = temLeft.next;
}else{
temRight.next = head;
temRight = temRight.next;
}
head = head.next;
}
temRight.next = null;//防止生成环形链表
temLeft.next = right.next;
return left.next;
}
}