国产xxxx99真实实拍_久久不雅视频_高清韩国a级特黄毛片_嗯老师别我我受不了了小说

資訊專欄INFORMATION COLUMN

[LintCode] Insert Node in Sorted Linked List

littleGrow / 2550人閱讀

Problem

Insert a node in a sorted linked list.

Example

Given list = 1->4->6->8 and val = 5.

Return 1->4->5->6->8.

Solution
public class Solution {
    public ListNode insertNode(ListNode head, int val) {
        
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode node = new ListNode(val);
        
        //if val is the smallest in entire list
        if (head == null || val < head.val) {
            dummy.next = node;
            node.next = head;
            return dummy.next;
        }
        
        //while val is larger than head.val, loop the linked list and check the range between head & head.next to insert
        while (head != null && head.next != null) {
            if (head.val <= val && val <= head.next.val) {
                ListNode next = head.next;
                head.next = node;
                node.next = next;
                break;
            } else if (val > head.next.val) {
                head = head.next;
            }
        }
        
        //if node not inserted in the loop
        if (head.next == null) {
            head.next = node;
        }

        return dummy.next;
    }
}

文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。

轉(zhuǎn)載請注明本文地址:http://specialneedsforspecialkids.com/yun/68069.html

相關(guān)文章

  • [LintCode] Insert into a Cyclic Sorted List

    Problem Given a node from a cyclic linked list which has been sorted, write a function to insert a value into the list such that it remains a cyclic sorted list. The given node can be any single node ...

    Acceml 評論0 收藏0
  • [LintCode] Remove Duplicates form Sorted List I &a

    摘要:和上一道題不同的地方就是,需要用雙指針操作,且最后要返回,以防止結(jié)點即的情況返回錯誤的結(jié)果。令,用進行查重操作,是的前結(jié)點。當(dāng)和等值的時候,后移至第一個不等值的點,用指向新的即可。 Remove Duplicates form Sorted List I Problem Given a sorted linked list, delete all duplicates such tha...

    int64 評論0 收藏0
  • [LintCode/LeetCode] Merge Two Sorted Lists

    摘要:先考慮和有無空集,有則返回另一個。新建鏈表,指針將和較小的放在鏈表頂端,然后向后遍歷,直到或之一為空。再將非空的鏈表放在后面。 Problem Merge two sorted (ascending) linked lists and return it as a new sorted list. The new sorted list should be made by splici...

    dockerclub 評論0 收藏0
  • [LeetCode] 708. Insert into a Cyclic Sorted List

    Problem Given a node from a cyclic linked list which is sorted in ascending order, write a function to insert a value into the list such that it remains a cyclic sorted list. The given node can be a r...

    qpwoeiru96 評論0 收藏0
  • [LintCode/LeetCode] Convert Sorted List to Balance

    摘要:當(dāng)鏈表為空時,中出現(xiàn)大于,返回。然后計算中點,以為界分別遞歸構(gòu)建左右子樹。順序是,左子樹根結(jié)點右子樹。由于根節(jié)點是直接取構(gòu)建,當(dāng)前的已經(jīng)被取用。所以在下一次遞歸構(gòu)建右子樹之前,要讓指向。最后將和左右子樹相連,返回。 Problem Given a singly linked list where elements are sorted in ascending order, conve...

    Michael_Ding 評論0 收藏0

發(fā)表評論

0條評論

最新活動
閱讀需要支付1元查看
<