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 in the list. Return the inserted new node.
Notice3->5->1 is a cyclic list, so 3 is next node of 1.
3->5->1 is same with 5->1->3
Given a list, and insert a value 4:
3->5->1
Return 5->1->3->4
Amazon Linked List
Solutionpublic class Solution { public ListNode insert(ListNode node, int x) { ListNode head = node; if (node == null) { node = new ListNode(x); node.next = node; return node; } if (node.next == head) { insertNode(node, x); return head; } while (node != null && node.next != null) { if (node.val < node.next.val) { if (node.val <= x && x <= node.next.val) { insertNode(node, x); break; } } else if (node.val > node.next.val) { if (x >= node.val || x <= node.next.val) { insertNode(node, x); break; } } else { if (node.next == head) { insertNode(node, x); break; } } node = node.next; } return head; } public void insertNode(ListNode head, int x) { ListNode node = new ListNode(x); node.next = head.next; head.next = node; } }
文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。
轉載請注明本文地址:http://specialneedsforspecialkids.com/yun/68098.html
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...
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...
摘要:建立兩個堆,一個堆就是本身,也就是一個最小堆另一個要寫一個,使之成為一個最大堆。我們把遍歷過的數組元素對半分到兩個堆里,更大的數放在最小堆,較小的數放在最大堆。同時,確保最大堆的比最小堆大,才能從最大堆的頂端返回。 Problem Numbers keep coming, return the median of numbers at every time a new number a...
Problem Given two sorted integer arrays A and B, merge B into A as one sorted array. Notice You may assume that A has enough space (size that is greater or equal to m + n) to hold additional elements ...
摘要:循環里最好先考慮和其中之一已經處理完的情況,就直接順序放另一個沒處理完的即可。然后再在里展開方法。避免其中一個數組較小會浪費效率的情況。丫把參數又換成了。。。 Problem Merge two given sorted integer array A and B into a new sorted integer array. Example A=[1,2,3,4] B=[2,4,5...
閱讀 2650·2023-04-26 00:42
閱讀 2799·2021-09-24 10:34
閱讀 3810·2021-09-24 09:48
閱讀 4145·2021-09-03 10:28
閱讀 2577·2019-08-30 15:56
閱讀 2771·2019-08-30 15:55
閱讀 3254·2019-08-29 12:46
閱讀 2244·2019-08-28 17:52