Insert a node in a sorted linked list.

/**
 * Created by qjb on 2016/1/30.
 *
 * Insert a node in a sorted linked list.
 *
 * Example
 * Given list = 1->4->6->8 and val = 5.
 * Return 1->4->5->6->8.
 *
 * 1、插入Node的核心代碼很簡單:node.next = head.next;   head.next = node;這個腦袋裏有圖,理解了先指向哪個,後指向哪個就可以了
 * 2、head是reference,這樣隨着遍歷,head會變化,但題目要求不只是插入節點,而且要返回鏈表,所以必須在head變化前保存head的值,
 * 以便最後返回;
 * 3、head.next!=null判斷,這個必須有;因爲要處理鏈表的內容,必須要拿到處理位置的上一個節點,這樣才能獲得head,head.next兩個
 * 節點,也就是上下文,才能做插入處理;
 *
 * 總結:
 * 1、鏈表遍歷模板:
 * while (condition) {
 *     head = head.next;
 *}
 *
 * 2、鏈表插入模板:
 *  node.next = head.next;
 *  head.next = node;
 *
 */

class ListNode {
     int val;
     ListNode next;
     ListNode(int x) {
         val = x;
         next = null;
     }
 }
public class Solution {

    public ListNode insertNode(ListNode head, int val) {
        ListNode node = new ListNode(val);
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        head = dummy;

        // find the last element <= val
        while (head.next != null && head.next.val <= val) {
            head = head.next;
        }
        node.next = head.next;
        head.next = node;

        return dummy.next;
    }

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章