Link: https://oj.leetcode.com/problems/partition-list/
这是CC150原题,我的思路正确,但代码有问题。再做。
Time: O(n), Space: O(1)
我的代码:
public class Solution {
//CC150
public ListNode partition(ListNode head, int x) {
if(head == null) return null;
ListNode sHead = null;//small
ListNode sTail = null;
ListNode lHead = null;//large
ListNode lTail = null;
while(head != null){
if(head.val < x){
sTail.next = head;
sTail = sTail.next;
}
else{
lTail.next = head;
lTail = lTail.next;
}
head = head.next;
}
sTail.next = lHead;
return sHead.next;
}
}
正确答案:
主要错误是:
sTail.next = lHead;
改成
sTail.next = lHead.next;
public class Solution {
//CC150
public ListNode partition(ListNode head, int x) {
if(head == null) return null;
ListNode sHead = new ListNode(-1);//small
ListNode sTail = sHead;
ListNode lHead = new ListNode(-1);//large
ListNode lTail = lHead;
while(head != null){
if(head.val < x){
sTail.next = head;
sTail = sTail.next;
}
else{
lTail.next = head;
lTail = lTail.next;
}
head = head.next;
}
sTail.next = lHead.next;
lTail.next = null;
return sHead.next;
}
}