【LeetCode】86. Partition List 分隔链表(Medium)(JAVA)
题目地址: https://leetcode.com/problems/partition-list/
题目描述:
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.
Example:
Input: head = 1->4->3->2->5->2, x = 3
Output: 1->2->2->4->3->5
题目大意
给定一个链表和一个特定值 x,对链表进行分隔,使得所有小于 x 的节点都在大于或等于 x 的节点之前。
你应当保留两个分区中每个节点的初始相对位置。
解题方法
- 用两个链表分别存储比 x 小的数和比 x 大的数
- 最后把两个链表合起来即可
class Solution {
public ListNode partition(ListNode head, int x) {
ListNode small = new ListNode();
ListNode smallPre = small;
ListNode big = new ListNode();
ListNode bigPre = big;
while (head != null) {
ListNode next = head.next;
head.next = null;
if (head.val < x) {
smallPre.next = head;
smallPre = head;
} else {
bigPre.next = head;
bigPre = head;
}
head = next;
}
smallPre.next = big.next;
return small.next;
}
}
执行耗时:0 ms,击败了100.00% 的Java用户
内存消耗:37.8 MB,击败了50.35% 的Java用户