/** * Definition for ListNode * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */publicclassSolution { /** * @param head: The head of linked list. * @param val: An integer. * @return: The head of new linked list. */publicListNodeinsertNode(ListNode head,int val) {ListNode dummy =newListNode(0);dummy.next= head;ListNode cur = dummy;while (cur.next!=null&&cur.next.val<= val) { cur =cur.next; }ListNode newNode =newListNode(val);newNode.next=cur.next;cur.next= newNode;returndummy.next; }}
Notes
Find the first node in the list after which the new node should be inserted.