[LeetCode 21]Merge Two Sorted Lists 合并两个有序链表

21. Merge Two Sorted Lists(合并两个有序链表)

Description

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.

Samples:

[1,2,3]

[2,5,6]

result

[1,2,2,3,5,6]

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };

 */

struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) {     struct ListNode *rethead;
    struct ListNode  *nextlist;
    int i=0;
    if(l1 == NULL ) return l2;
    if(l2 == NULL ) return l1;
    if(l1->val < l2->val){
       nextlist = l1;
       l1=l1->next; //必须要有,不然对于每个链表只有一个数的测试用例 [2] [1]死循环
    }else{
       nextlist = l2;
       l2=l2->next;
    }
    rethead= nextlist;
    while(l1 !=NULL  &&l2!=NULL) //等价于 while( l1 &&l2)
    {
        if(l1->val < l2->val){
          nextlist->next = l1;
          l1 = l1->next;
        }else{
          nextlist->next = l2;
          l2 = l2->next;
        }
        nextlist = nextlist ->next;
      
    }
    if(l1)  nextlist->next = l1;
    else  nextlist->next = l2;
    return rethead;
 

}



其实这个算法题的官方实现有个bug就是只针对升序的lists,如下图。对于降序的例子结果是错误的。其实可以根据其中一个list的前两个数确定升序还是降序,在分支中实现不同的条件比较和其他语句。


[LeetCode 21]Merge Two Sorted Lists 合并两个有序链表_第1张图片

你可能感兴趣的:(算法)