[leetcode]86. Partition List划分链表

时间:2021-11-06 12:37:17

Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.

You should preserve the original relative order of the nodes in each of the two partitions.

Input: head = 1->4->3->2->5->2, x = 3
Output: 1->2->2->4->3->5

题意:

给定一个链表和一个值,把小于等于和大于该值的部分分别放到链表的一前一后去。

思路:

先分为两个链表

然后合并

代码:

 class Solution {
public ListNode partition(ListNode head, int x) {
ListNode leftDummy = new ListNode(-1);
ListNode rightDummy = new ListNode (-1);
ListNode left_cur = leftDummy;
ListNode right_cur = rightDummy;
ListNode cur = head; while( cur != null){
if(cur.val < x){
left_cur.next = cur;
left_cur = cur;
}else{
right_cur.next = cur;
right_cur = cur;
}
cur = cur.next;
}
left_cur.next = rightDummy.next;
right_cur.next = null;
return leftDummy.next;
}