给你一个linkedlist,比如说 1 -> 2 -> -3 -> -5 -> 6, 已经按照绝对值大小排序。 让你返回按照正常顺序排好的linkedlist。 Time complexity: O(n), space O(1)

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        head = dummy;
        // if ndoe is negative, remove node from its original location.
        // if ndoe is negative, add to head. ptr = head.next, head.next, node.next = ptr.
        while (head.next != null) {
            if (head.next.val < 0) {
                ListNode temp = head.next;
                head.next = temp.next;
                temp.next = dummy.next;
                dummy.next = temp;
            } else {
                head = head.next;
            }
        }
        return dummy.next;
    }
}
Advertisements