一、题目描述
给定一个链表和一个特定值 x,对链表进行分隔,使得所有小于 x 的节点都在大于或等于 x 的节点之前。
你应当保留两个分区中每个节点的初始相对位置。
示例:
输入: head = 1->4->3->2->5->2, x = 3
输出: 1->2->2->4->3->5
二、解题思路
通过两个虚拟的头节点,分别作为两个链表的头部,其中一个链表用于存储比x小的元素,另外一个链表存储大于等于x的元素。从前往后遍历链表,每次将遍历到的节点连接到上述两个链表中对应的尾部,最后将小于x的链表和大于等于x的链表连在一起去掉各自的虚拟头部即可。
三、代码
/**
* 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 little=new ListNode();
ListNode lc=little;
ListNode big=new ListNode();
ListNode bc=big;
ListNode cur=head;
while(cur!=null){
if(cur.val<x){
lc.next=cur;
lc=lc.next;
}else{
bc.next=cur;
bc=bc.next;
}
cur=cur.next;
}
lc.next=big.next;
bc.next=null;
return little.next;
}
}
四、结果
0ms,100%