Note: 存在两种情况,插入的新node插在头,或插在中间
public class Solution {
public ListNode insert(ListNode head, int value) {
ListNode newNode = new ListNode(value);
if (head == null || head.value > value) {
newNode.next = head;
return newNode;
}
ListNode cur = head;
while (cur.next != null && cur.next.value < value) {
cur = cur.next;
}
ListNode next = cur.next;
cur.next = newNode;
newNode.next = next;
return head;
}
}
Complexity Analysis:
TC: O(n)
SC: O(1)