Insert Node in Sorted Linked List
题目:
Insert a node in a sorted linked list.
Given list = 1->4->6->8 and val = 5.
Return 1->4->5->6->8.
分析:
注意一下添加在最后的时候怎么处理
解法:
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 dummy = new ListNode(-1);
dummy.next = head;
ListNode curr = dummy;
while (curr != null) {
if (curr.next == null || curr.next.val > val) {
ListNode temp = new ListNode(val);
temp.next = curr.next;
curr.next = temp;
break;
}
curr = curr.next;
}
return dummy.next;
}
}