题目
分析
题目的意思是将小于x的节点全部放在大于或者等于x节点的左侧,且节点之间的相对位置不发发生改变。
思路:
首先设置两个指针slow和fast,slow指针指示小于x的节点,fast指针指示大于或者等于x的节点,遍历链表,如果当前节点值小于x,则将其加入到slow节点后,同时更新slow指向当前节点,否则将当前节点加入到fast后,更新fast指向当前节点。
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* }
*/
public class Solution {
/**
*
* @param head ListNode类
* @param x int整型
* @return ListNode类
*/
public ListNode partition (ListNode head, int x) {
// write code here
//头结点
ListNode head1 = new ListNode(-1);
ListNode slow = head1;
ListNode fast = head1;
ListNode n = head;
//指示是否遇到第一个大于或者等于x节点的值,在没有遇到之前,fast和slow同步更新
boolean bool = true;
while(n != null) {
if(n.val < x) {
ListNode temp = n.next;
n.next = slow.next;
slow.next = n;
slow = n;
if(bool == true) {
fast = slow;
}
n = temp;
} else {
bool = false;
ListNode temp = n.next;
n.next = fast.next;
fast.next = n;
fast = n;
n = temp;
}
}
return head1.next;
}
}