【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;

 /**
* 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) {
if (l1 == NULL) return l2;
if (l2 == NULL) return l1; ListNode* prehead = new ListNode();
ListNode* newlist = prehead; while (l1 != NULL && l2 != NULL) {
if (l1->val > l2->val) {
newlist->next = l2;
l2 = l2->next;
} else {
newlist->next = l1;
l1 = l1->next;
}
newlist = newlist->next;
} if (l1 == NULL) newlist->next = l2;
else newlist->next = l1; l1 = prehead->next;
delete prehead;
return l1;
}
};
上一篇:iOS 笔试题


下一篇:深度分析ORACLE热点块问题