Insert_Node_In_Sorted_LinkedList

Question

Insert a node in a sorted linked list.

Example:

Given list = 1->4->6->8 and val = 5.

Return 1->4->5->6->8.

Lessons Learned:

There are some important stuffs to remember:

  • I got wrong here too. You cannot left head, because head is the main field of the LinkedList. So you need to properly handle that, not just let the ListNode insert be the Linkedlist. It is not the field of the Linked List!
          if (head == null) {
              insert.next = head;
              head = insert;
              return head;
          }
    
  • // I got wrong here! It is hard to deside assign what to what@@

              cur.next = insert;
              return head;
    
  • This question is required to return the ListNode. The only ListNode that make sense to the LinkedList object is head. So it makes no sense return insert. You must return head.

    /**

    • Definition for ListNode
    • public class ListNode {
    • int val;
    • ListNode next;
    • ListNode(int x) {
    • val = x;
    • next = null;
    • }
    • } / public class Solution { /*

      • @param head: The head of linked list.
      • @param val: an integer
      • @return: The head of new linked list */ public ListNode insertNode(ListNode head, int val) { // Write your code here ListNode insert = new ListNode(val);

        // I got wrong here too. You cannot left head, because head is the main field of the LinkedList. So you need to properly handle that, not just let the ListNode insert be the Linkedlist. It is not the field of the Linked List! if (head == null) {

         insert.next = head;
         head = insert;
         return head;
        

        }

        ListNode cur = head; if (val < cur.val) {

         insert.next = cur;
         head = insert;
         return head;
        

        } else {

         while (cur.next != null) {
             if (val < cur.next.val) {
                 ListNode next = cur.next;
        
                 cur.next = insert;
                 insert.next = next;
                 return head;
             }
             cur = cur.next;
         }
         // I got wrong here! It is hard to deside assign what to what@@
         cur.next = insert;
         return head;
        

        } }
        }