题目地址:
https://www.lintcode.com/problem/insert-node-in-sorted-linked-list/description
给定一个有序链表,向其插入一个数使其仍然保持有序。思路很简单,只需要先寻找要插入的位置即可。代码如下:
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) {
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode cur = dummy;
while (cur.next != null && cur.next.val < val) {
cur = cur.next;
}
ListNode insertion = new ListNode(val);
insertion.next = cur.next;
cur.next = insertion;
return dummy.next;
}
}
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}
时间复杂度 ,空间 。