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