zoukankan      html  css  js  c++  java
  • 219. Insert Node in Sorted Linked List【Naive】

    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  * Definition of ListNode
     3  * class ListNode {
     4  * public:
     5  *     int val;
     6  *     ListNode *next;
     7  *     ListNode(int val) {
     8  *         this->val = val;
     9  *         this->next = NULL;
    10  *     }
    11  * }
    12  */
    13 
    14 
    15 class Solution {
    16 public:
    17     /*
    18      * @param head: The head of linked list.
    19      * @param val: An integer.
    20      * @return: The head of new linked list.
    21      */
    22     ListNode * insertNode(ListNode * head, int val) {
    23         ListNode * new_node = new ListNode(val);
    24         if (head == NULL) {
    25             return new_node;
    26         }
    27         
    28         ListNode * dummy = new ListNode(-1);
    29         dummy->next = head;
    30         head = dummy;
    31         
    32         while (head->next != NULL) {
    33             if (val > head->next->val) {
    34                 head = head->next;
    35             } else {
    36                 new_node->next = head->next;
    37                 head->next = new_node;
    38                 break;
    39             }
    40         }
    41         
    42         if (head->next == NULL) {
    43             head->next = new_node;
    44         }
    45         
    46         return dummy->next;
    47     }
    48 };

    经典的构造dummy头节点问题

  • 相关阅读:
    最近的一些心理活动
    object_c函数多个返回值
    nslayoutConstraint
    判断一些常用的东西
    color 的一些处理
    最近的心理活动
    加载不同的nib文件
    Be a person
    按钮居左显示
    SQLite错误码
  • 原文地址:https://www.cnblogs.com/abc-begin/p/8409079.html
Copyright © 2011-2022 走看看