Leetcode 线性表 Merge Two Sorted Lists

来源:互联网 发布:软件创新设计方案 编辑:程序博客网 时间:2024/04/30 20:28

本文为senlie原创,转载请保留此地址:http://blog.csdn.net/zhengsenlie


Merge Two Sorted Lists

 Total Accepted: 14176 Total Submissions: 44011

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.



题意:将两个已排好序的链接合并成一个有序链表
思路:归并排序的合并步骤,用两个指针分别指向两个链表,
每次新链表的指针指向值小的那个节点,并分别前进该节点的链表指针和新链表的指针
遍历的次数为短链表的长度
遍历后把新链表的指针指向长链表的剩余部分
小技巧:刚开始的时候,cur指针为NULL,cur->next未定义,可以使用一个dummy变量,让l3和cur指向该变量
返回值的时候,再把l3前移一步就可以了。

复杂度:时间O(m+n), 空间O(1)


/** * 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) return l2;    if(!l2) return l1;    ListNode *l3, *cur;    ListNode dummy(-1);    l3 = cur = &dummy;    while(l1&&l2){    if(l1->val < l2->val) {    cur->next = l1;    l1 = l1->next;    }else{    cur->next = l2;    l2 = l2->next;    }    cur = cur->next;    }    if(l1) cur->next = l1;    else cur->next = l2;    return l3->next;        }};


0 0