/**
* 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;
}
}
Insert a node in a sorted linked list.
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章
吸血鬼數字求解
strike1989
2020-07-04 10:01:49
(poj)Catch That Cow
CSwhit
2020-06-25 12:00:37
算法初級(四)——單鏈表
我惠依旧
2020-05-14 10:16:47
算法初級(三)——線性表
我惠依旧
2020-05-14 10:16:47
求a[j]-a[i]的最大值,其中j>=i
strike1989
2020-02-21 18:56:40
尋找一個數組中的主元素
strike1989
2020-02-21 18:56:40
Ultra-QuickSort
CSwhit
2018-11-04 10:38:53
用python實現將數組元素按從小到大的順序排列
llx1026
2018-09-03 02:17:54
使用python實現二分查找
llx1026
2018-09-03 02:17:54
Valid Palindrome
jiabin_qiao
2018-08-31 18:52:26
Reverse Integer
jiabin_qiao
2018-08-31 18:52:25
輸入n,輸出所有的n元排列
Silicified_wood
2018-08-30 10:29:15
24小時熱門文章