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

(链表) lintcode 219. Insert Node in Sorted Linked List

时间:2019-04-23 19:25:46      阅读:134      评论:0      收藏:0      [点我收藏+]

标签:size   break   rip   mic   render   c++   code   public   out   

Description

 

Insert a node in a sorted linked list.

Example

Example 1:

Input: head = 1->4->6->8->null, val = 5
Output: 1->4->5->6->8->null

Example 2:

Input: head = 1->null, val = 2
Output: 1->2->null
---------------------------------------------------------------------


就是在一个有序的链表中插入一个数。
C++代码:
注意有表头,表中间和表尾三个情况
/**
 * Definition of singly-linked-list:
 * class ListNode {
 * public:
 *     int val;
 *     ListNode *next;
 *     ListNode(int val) {
 *        this->val = val;
 *        this->next = NULL;
 *     }
 * }
 */

class Solution {
public:
    /**
     * @param head: The head of linked list.
     * @param val: An integer.
     * @return: The head of new linked list.
     */
    ListNode * insertNode(ListNode * head, int val) {
        // write your code here
        ListNode *cur = new ListNode(val);
        ListNode *dummy = new ListNode(-1);
        dummy->next = head;
        if(!head) return cur;
        ListNode *p = dummy;
        while(p->next){
            if(p->next->val > val)
                break;
            else
                p = p->next;
        }
        cur->next = p->next;
        p->next = cur;
        return dummy->next;
    }
};

 



(链表) lintcode 219. Insert Node in Sorted Linked List

标签:size   break   rip   mic   render   c++   code   public   out   

原文地址:https://www.cnblogs.com/Weixu-Liu/p/10758074.html

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