Problem
Insert a node in a sorted linked list.
ExampleGiven list = 1->4->6->8 and val = 5.
Return 1->4->5->6->8.
Solutionpublic 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
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 ...
摘要:和上一道題不同的地方就是,需要用雙指針操作,且最后要返回,以防止結(jié)點即的情況返回錯誤的結(jié)果。令,用進行查重操作,是的前結(jié)點。當(dāng)和等值的時候,后移至第一個不等值的點,用指向新的即可。 Remove Duplicates form Sorted List I Problem Given a sorted linked list, delete all duplicates such tha...
摘要:先考慮和有無空集,有則返回另一個。新建鏈表,指針將和較小的放在鏈表頂端,然后向后遍歷,直到或之一為空。再將非空的鏈表放在后面。 Problem Merge two sorted (ascending) linked lists and return it as a new sorted list. The new sorted list should be made by splici...
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...
摘要:當(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...
閱讀 1403·2021-10-11 10:59
閱讀 3104·2019-08-30 15:54
閱讀 2724·2019-08-30 13:19
閱讀 2456·2019-08-30 13:02
閱讀 2372·2019-08-30 10:57
閱讀 3347·2019-08-29 15:40
閱讀 981·2019-08-29 15:39
閱讀 2300·2019-08-29 12:40