/**
* 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;
}
}
* 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;
}
}