码迷,mamicode.com
首页 > 其他好文 > 详细

219. Insert Node in Sorted Linked List【Naive】

时间:2018-02-03 16:03:35      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:list   pos   class   ane   and   next   构造   ==   bsp   

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 List【Naive】

标签:list   pos   class   ane   and   next   构造   ==   bsp   

原文地址:https://www.cnblogs.com/abc-begin/p/8409079.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!