分隔链表
解法一:链表遍历
public class LeetCode_086 {
public static ListNode partition(ListNode head, int x) {
// 小于x的链表节点
ListNode lessThan = new ListNode(-1);
// 不小于x的链表节点
ListNode moreThan = new ListNode(-1);
ListNode curLess = lessThan, curMore = moreThan;
while (head != null) {
if (head.val < x) {
// 小于x的节点添加到链表lessThan中
curLess.next = head;
curLess = curLess.next;
} else {
// 不小于x的节点添加到链表moreThan中
curMore.next = head;
curMore = curMore.next;
}
head = head.next;
}
// 所有节点遍历完成后将lessThan和moreThan尾结点指向null
curLess.next = null;
curMore.next = null;
// 将小于x的节点挪到不小于x的节点的前面
curLess.next = moreThan.next;
return lessThan.next;
}
public static void main(String[] args) {
ListNode head = new ListNode(1);
head.next = new ListNode(4);
head.next.next = new ListNode(3);
head.next.next.next = new ListNode(2);
head.next.next.next.next = new ListNode(5);
head.next.next.next.next.next = new ListNode(2);
ListNode result = partition(head, 3);
while (result != null) {
System.out.print(result.val + " ");
result = result.next;
}
}
}