【Lintcode】219. Insert Node in Sorted Linked List

题目地址:

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

时间复杂度 O ( n ) O(n) ,空间 O ( 1 ) O(1)

发布了387 篇原创文章 · 获赞 0 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_46105170/article/details/105450544