zoukankan      html  css  js  c++  java
  • Insert Node in Sorted Linked List

    Insert a node in a sorted linked list.

    Example

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

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

    分析


    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    /**
     * Definition for ListNode
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) {
     *         val = x;
     *         next = null;
     *     }
     * }
     */
    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) { 
            // Write your code here
            ListNode dummy = new ListNode(0);
            ListNode node = new ListNode(val);
            dummy.next = head;
             
            ListNode pos = dummy;
            ListNode next = head;
             
            while(pos.next != null && pos.next.val < val){
                pos = pos.next;
                next = next.next;
            }
             
            node.next = next;
            pos.next = node;
             
            return dummy.next;
        }  
    }




  • 相关阅读:
    牛客练习赛44 A 小y的序列 (模拟,细节)
    牛客假日团队赛10 L 乘积最大 (dp,大数)
    三分查找
    几何基础知识点
    POJ 2318 TOYS
    UVA 11916 Emoogle Grid(大步小步算法(解模方程对数) 快速幂 模的逆)
    UVA 11426 GCD
    Aladdin and the Flying Carpet(算术基本定理)
    算术基本定理
    数论总结帖
  • 原文地址:https://www.cnblogs.com/zhxshseu/p/22742241775e13d131fe378c45f70fea.html
Copyright © 2011-2022 走看看