【Leetcode】【Easy】Merge Two Sorted Lists .
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
解题:
题目比较简单,注意由于表头不确定,因此新建一个结点指向新创建的链表;
解题步骤:
1、判断l1和l2是否有效
2、新建preHead结点,newlist指针指向preHead;
3、循环开始,满足l1和l2都不为空:
(1)比较当前l1和l2的值,将较小的穿进newlist中
4、newlist链接l1或l2的剩余部分
5、释放表头,返回newlist;
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { 12 if (l1 == NULL) return l2; 13 if (l2 == NULL) return l1; 14 15 ListNode* prehead = new ListNode(0); 16 ListNode* newlist = prehead; 17 18 while (l1 != NULL && l2 != NULL) { 19 if (l1->val > l2->val) { 20 newlist->next = l2; 21 l2 = l2->next; 22 } else { 23 newlist->next = l1; 24 l1 = l1->next; 25 } 26 newlist = newlist->next; 27 } 28 29 if (l1 == NULL) newlist->next = l2; 30 else newlist->next = l1; 31 32 l1 = prehead->next; 33 delete prehead; 34 return l1; 35 } 36 };