资讯专栏INFORMATION COLUMN

[LintCode] Insert Node in Sorted Linked List

littleGrow / 2612人阅读

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

</>复制代码

  1. public class Solution {
  2. public ListNode insertNode(ListNode head, int val) {
  3. ListNode dummy = new ListNode(0);
  4. dummy.next = head;
  5. ListNode node = new ListNode(val);
  6. //if val is the smallest in entire list
  7. if (head == null || val < head.val) {
  8. dummy.next = node;
  9. node.next = head;
  10. return dummy.next;
  11. }
  12. //while val is larger than head.val, loop the linked list and check the range between head & head.next to insert
  13. while (head != null && head.next != null) {
  14. if (head.val <= val && val <= head.next.val) {
  15. ListNode next = head.next;
  16. head.next = node;
  17. node.next = next;
  18. break;
  19. } else if (val > head.next.val) {
  20. head = head.next;
  21. }
  22. }
  23. //if node not inserted in the loop
  24. if (head.next == null) {
  25. head.next = node;
  26. }
  27. return dummy.next;
  28. }
  29. }

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/68069.html

相关文章

  • [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

    摘要:和上一道题不同的地方就是,需要用双指针操作,且最后要返回,以防止结点即的情况返回错误的结果。令,用进行查重操作,是的前结点。当和等值的时候,后移至第一个不等值的点,用指向新的即可。 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

    摘要:当链表为空时,中出现大于,返回。然后计算中点,以为界分别递归构建左右子树。顺序是,左子树根结点右子树。由于根节点是直接取构建,当前的已经被取用。所以在下一次递归构建右子树之前,要让指向。最后将和左右子树相连,返回。 Problem Given a singly linked list where elements are sorted in ascending order, conve...

    Michael_Ding 评论0 收藏0

发表评论

0条评论

littleGrow

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<