- Insert Node in Sorted Linked List
中文English
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
解法1:
代码如下:
/**
* 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) {
if (!head) return new ListNode(val);
ListNode * newNode = new ListNode(val);
if (val < head->val) {
newNode->next = head;
return newNode;
}
ListNode * node = head;
while(node && node->next) {
if (val >= node->val && val < node->next->val) {
newNode->next = node->next;
node->next = newNode;
break;
}
node = node->next;
}
node->next = newNode;
return head;
}
};