/**
* Definition of singly-linked-list:
* class ListNode {
* public:
* int val;
* ListNode *next;
* ListNode(int val) {
* this->val = val;
* this->next = NULL;
* }
* }
*/
方法一:对原有链表进行拼接完成。太慢!!!!!!
class Solution {
public:
/**
* @param l1: ListNode l1 is the head of the linked list
* @param l2: 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
if(l1 == NULL){
return l2;
}
if (l2 == NULL){
return l1;
}
if(l1->val > l2->val){
ListNode *temp = l1;
l1 = l2;
l2 = temp;
}
ListNode *head = l1;
ListNode *q = l2;
while (l2 != NULL && l1->next != NULL){
if (l1->val <= l2->val && l1->next->val >= l2->val){
q = q->next;
l2->next = l1->next;
l1->next = l2;
l1 = l1->next;
l2 = q;
}
else{
l1 = l1->next;
}
}
if (l2 != NULL){
l1->next = l2;
}
return head;
}
};
方法二:新建一个链表。少了1000ms,已经是三种方法里面最快的了!
class Solution {
public:
/**
* @param l1: ListNode l1 is the head of the linked list
* @param l2: 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 = new ListNode(0);
ListNode *p = head;
while(l1 != NULL && l2 != NULL){
if(l1->val <= l2->val){
p->next = new ListNode(l1->val);
p = p->next;
l1 = l1->next;
}
else if(l1->val > l2->val){
p->next = new ListNode(l2->val);
p = p->next;
l2 = l2->next;
}
}
if (l1 == NULL){
p->next = l2;
}
if (l2 == NULL){
p->next = l1;
}
return head->next;
}
};
方法三:递归。阿勒阿勒,7000多ms,没想到更慢了!!!不过感觉方法很逼格!
class Solution {
public:
/**
* @param l1: ListNode l1 is the head of the linked list
* @param l2: 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 = NULL;
if (l1 == NULL){
return l2;
}
if (l2 == NULL){
return l1;
}
if(l1->val <= l2->val){
head = l1;
l1->next = mergeTwoLists(l1->next, l2);
}
if(l1->val > l2->val){
head = l2;
l2->next = mergeTwoLists(l1, l2->next);
}
return head;
}
};