Insert In Sorted Linked List (LaiCode)

//class ListNode { // public: // int value; // ListNode* next; // ListNode(int v) : value(v), next(NULL) {} //}; class Solution { public: ListNode* insert(ListNode* head, int value) { // write your solution here ListNode * newnode = new ListNode(value); if (head == nullptr){ head = newnode; return head; } ListNode * dummy = new ListNode(0); dummy->next = head; ListNode * insert = dummy; // insert after "insert" node while(insert->next != nullptr && insert->next->value < value) insert = insert->next; if (insert->next == nullptr) insert->next = newnode; else{ newnode->next = insert->next; insert->next = newnode; } return dummy->next; } };
Mistake:
- Note when insert approaches the end, what if its next is nullptr? No need to update "next" in this case.

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.