描述
给定一个单链表和数值x,划分链表使得所有小于x的节点排在大于等于x的节点之前。
你应该保留两部分内链表节点原有的相对顺序。
样例
样例 1:
输入: list = null, x = 0
输出: null
样例解释: 空链表本身满足要求
样例 2:
输入: list = 1->4->3->2->5->2->null, x = 3
输出: 1->2->2->4->3->5->null
样例解释: 要保持原有的相对顺序。
代码部分
/**
* Definition for ListNode
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
/**
* @param head: The first node of linked list
* @param x: An integer
* @return: A ListNode
*/
public ListNode partition(ListNode head, int x) {
// write your code here
if(head==null)return null;
ListNode reslowDummy=new ListNode(0);
ListNode reshighDummy=new ListNode(0);
ListNode reslow=reslowDummy;
ListNode reshigh=reshighDummy;
while(head!=null){
if(head.val<x){
reslowDummy.next=head;
reslowDummy=head;
}
else if(head.val>=x){
reshighDummy.next=head;
reshighDummy=head;
}
head=head.next;
}
//拼接
if(reshighDummy.val<x){
reslowDummy.next=null;
}
else{
reshighDummy.next=null;
}
reslowDummy.next=reshigh.next;
return reslow.next;
}
}
补充说明
if(reshighDummy.val<x){
reslowDummy.next=null;
}
else{
reshighDummy.next=null;
}
最后需要给最后节点的下一个节点赋值null!!最开始没有写这段代码,报错java.lang.NullPointerException,需要注意。