0
public LinkedIntList splitBySign() {
    LinkedIntList res = new LinkedIntList();
    ListNode back = res.front;
    while (front != null && front.data < 0) {
        ListNode temp = front;
        front = front.next;
        temp.next = null;
        if (back == null) {
            res.front = temp;
        } else {
            back.next = temp;
            back = back.next;
        }
    }
    ListNode curr = front;
    while (curr != null && curr.next != null) {
        if (curr.next.data < 0) {
            ListNode temp = curr.next;
            curr.next = temp.next;
            temp.next = null;
            if (back == null) {
                res.front = temp;
            } else {
                back.next = temp;
                back = back.next;
            }
        } else {
            curr = curr.next;
        }
    }
    return res;
}

This method is intended to split a LinkedIntList so that all negative values will be removed to another LinkedIntList and finally return the created LinkedIntList. However when I actually run this code, the test List is [-1, -1, -2, -3, 3, 0, 1, 2, 3], the change of the original list is the expected [3, 0, 1, 2, 3], but the returned list is [-3] instead of [-1, -1, -2, -3].

xunmiw
  • 31
  • 3
  • After `res = new LinkedIntList()` you do `back = res.front`. Why? You just created it, so `res.front` is null, so why not just `back = null`? --- In the first loop, you do `if (back == null) { res.front = temp; } else ...`. We just established that `back` *is* null, so the `if` block executes. `back` is still null, so on second iteration, the `if` block executes again. `back` is still null, so ... why even have an `if` statement if it's always true? --- [What is a debugger and how can it help me diagnose problems?](https://stackoverflow.com/q/25385173/5221149) – Andreas Nov 30 '19 at 00:20
  • Also, you seem to intend to take entries from the front of the list and add them to the end. Why would this process ever terminate? If you have proper `add` and `remove` methods in your list, this should be considerably easier. – Nico Schertler Nov 30 '19 at 00:22

0 Answers0