86. 分隔链表
给你一个链表和一个特定值 x
,请你对链表进行分隔,使得所有小于 x
的节点都出现在大于或等于 x
的节点之前。
你应当保留两个分区中每个节点的初始相对位置。
示例:
输入:head = 1->4->3->2->5->2, x = 3
输出:1->2->2->4->3->5
我的Java代码:
思路:找到第一个前后两节点分别小于和大于x的位置,作为插入点insert,遍历后续的节点,将小于x的节点插入insert后面,最后把剩余节点连在insert之后。
(代码质量比较差,有待优化)
/**
* 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 p = head, pre = p, insert, tail;
while(p != null && p.val < x) {
pre = p;
p = p.next;
}
if(p == null) {
return head;
}else if(p == head) {
tail = p;
while(p != null && p.val >= x) {
pre = p;
p = p.next;
}
if(p == null) {
return head;
}
insert = p;
head = insert;
p = p.next;
pre.next = p;
}else {
insert = pre;
tail = p;
}
while(p != null) {
if(p.val < x) {
insert.next = p;
insert = p;
p = p.next;
pre.next = p;
}else {
pre = p;
p = p.next;
}
}
insert.next = tail;
return head;
}
}
学习别人的代码:
力扣官方:
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/partition-list/solution/fen-ge-lian-biao-by-leetcode-solution-7ade/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
思路:直观来说我们只需维护两个链表 small 和 large 即可,small 链表按顺序存储所有小于 x 的节点,large 链表按顺序存储所有大于等于 x 的节点。遍历完原链表后,我们只要将 small 链表尾节点指向 large 链表的头节点即能完成对链表的分隔。
class Solution {
public ListNode partition(ListNode head, int x) {
ListNode small = new ListNode(0);
ListNode smallHead = small;
ListNode large = new ListNode(0);
ListNode largeHead = large;
while (head != null) {
if (head.val < x) {
small.next = head;
small = small.next;
} else {
large.next = head;
large = large.next;
}
head = head.next;
}
large.next = null;
small.next = largeHead.next;
return smallHead.next;
}
}
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/partition-list/solution/fen-ge-lian-biao-by-leetcode-solution-7ade/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。