219. Insert Node in Sorted Linked ListNaive

Posted abc_begin

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了219. Insert Node in Sorted Linked ListNaive相关的知识,希望对你有一定的参考价值。

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头节点问题

 

 

以上是关于219. Insert Node in Sorted Linked ListNaive的主要内容,如果未能解决你的问题,请参考以下文章

[LintCode] Insert Node in a Binary Search Tree

Insert Node in a Binary Search Tree

lintcode-easy-Insert Node in a Binary Search Tree

INSERT INTO 因 node-mysql 失败 - 变量始终为 NULL

219. Contains Duplicate II 超时

Deseja sua sorte boa, Renato Augusto