86. Partition List
题目
原始地址:https://leetcode.com/problems/partition-list/#/description

/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode partition(ListNode head, int x) {
}
}
描述
给定一个链表和一个值x,把链表分成两部分,值小于x的节点放到值大于等于x的节点之前。要求保留两部分中各节点之间的相对顺序不变。
分析
最简明的办法就是建立两个子链表,一个用来放值小于x的节点,另一个用来放值大于等于x的节点,最后把这两个子链表连起来即可。
需要注意最后要将新链表的尾节点的next置为null,否则将出现环的情况。
解法
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode partition(ListNode head, int x) {
ListNode h1 = new ListNode(0), h2 = new ListNode(0), l1 = h1, l2 = h2, curr = head;
while (curr != null) {
if (curr.val < x) {
l1.next = curr;
l1 = l1.next;
} else {
l2.next = curr;
l2 = l2.next;
}
curr = curr.next;
}
l1.next = h2.next;
l2.next = null;
return h1.next;
}
}

浙公网安备 33010602011771号