[LeetCode] Merge Two Sorted Lists
Merge Two Sorted Lists
Merge two sorted linked lists and return it as a new list. The new list shoshould be made by splicing together the nodes of the first two lists.
Solution:
This question is the easiest question for leetcode. One tips is to apply for a header node at the beginning and then delete it after merging. This makes the code clearer. The original space is used to accelerate the efficiency. The leetcode takes only 13 ms to run. Talk is cheap, show you the cade:
/*** Definition for singly-linked list. * struct ListNode {* int val; * ListNode * next; * ListNode (int x): val (x), next (NULL ){}*}; */class Solution {public: ListNode * mergeTwoLists (ListNode * l1, ListNode * l2) {ListNode * head = new ListNode (0); ListNode * p = head; // point to the last element of the fusion while (l1! = NULL & l2! = NULL) {if (l1-> val
Val) {p-> next = l1; p = l1; l1 = l1-> next;} else {p-> next = l2; p = l2; l2 = l2-> next;} while (l1! = NULL) {p-> next = l1; p = l1; l1 = l1-> next;} while (l2! = NULL) {p-> next = l2; p = l2; l2 = l2-> next;} p-> next = NULL; p = head; head = head-> next; delete p; return head ;}};