原题
解法1(参考别人,更简洁)
解题思路
将比X小的节点串成一串head1,将剩余的节点串成一串head2,最后将head1->head2
代码
public class Solution86 {
public ListNode partition(ListNode head, int x) {
if (head == null || head.next == null)
return head;
ListNode lessHead = new ListNode(0);
ListNode moreOrEqualHead = new ListNode(0);
ListNode iterator = head, lessIterator = lessHead, moreOrEqualIterator = moreOrEqualHead;
while (iterator != null){
if (iterator.val < x){
lessIterator.next = iterator;
lessIterator = lessIterator.next;
}
else {
moreOrEqualIterator.next = iterator;
moreOrEqualIterator = moreOrEqualIterator.next;
}
iterator = iterator.next;
}
moreOrEqualIterator.next = null;
lessIterator.next = moreOrEqualHead.next;
return lessHead.next;
}
}
解法2
解题思路
类似冒泡排序,将比x的值小的节点从尾部“冒泡”到前方:每一次将第i个节点插入到第0个到第i个节点之间的合适的位置,插入完毕后,前i个节点符合题目要求,执行N次,结束。
图解
Previous指向的为节点应该插入的位置,current节点与next节点用来判断节点是否需要移动以及存放移动时的信息。
代码
public class Solution {
public ListNode partition(ListNode head, int x) {
if (head == null || head.next == null)
return head;
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode previous = dummy, current;
while(previous.next != null && previous.next.val < x){
previous = previous.next;
}
current = previous;
while (current.next != null){
ListNode next = current.next;
if (current.next.val < x && current.val >= x){
current.next = next.next;
next.next = previous.next;
previous.next = next;
previous = previous.next;
}else {
current = current.next;
}
}
return dummy.next;
}
}