描述:将两个排序链表合并为一个新的排序链表
样例
给出 1->3->8->11->15->null
,2->null
, 返回 1->2->3->8->11->15->null
。
代码:/**
* Definition of ListNode
* class ListNode {
* public:
* int val;
* ListNode *next;
* ListNode(int val) {
* this->val = val;
* this->next = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param ListNode l1 is the head of the linked list
* @param ListNode l2 is the head of the linked list
* @return: ListNode head of linked list
*/
ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
// write your code here
ListNode *head, *p;
head= new ListNode(0);
p= head;
while (l1!= NULL || l2!= NULL) {
if (l1== NULL) {
p->next= l2;
p= l2;
l2= l2->next;
continue;
}
if (l2== NULL) {
p->next= l1;
p= l1;
l1= l1->next;
continue;
}
if (l1->val< l2->val) {
p->next= l1;
p= l1;
l1= l1->next;
} else {
p->next= l2;
p= l2;
l2= l2->next;
}
}
return head->next;
}
};
做题感想:当时刚开始做的时候,把这个问题想麻烦了,总想着要写的很麻烦来改变两个元素的位置。不过后来觉得这种方法很灵活。