您的位置:首页 > 其它

21. Merge Two Sorted Lists(Linked List)

2016-05-29 11:11 423 查看

Title

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.

Language C

/**
* Definition for singly-linked list.
* struct ListNode {
*     int val;
*     struct ListNode *next;
* };
*/
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) {
struct ListNode *head, *h, *p, *q;
head = (struct ListNode *)malloc(sizeof(struct ListNode));
head->val = 0;
head->next = NULL;
h = head;
p = l1;
q = l2;
while(p != NULL && q != NULL){
if(p->val >= q->val) {
h->next = q;
q = q->next;
}
else {
h->next = p;
p = p->next;
}
h = h->next;
// h->next = NULL;
}
if(p != NULL){
h->next = p;
}
if(q != NULL){
h->next = q;
}
return head->next;
}


runtime:4ms

思路

将两个已排好序的链表合并为一个新的链表

1. 建立新链表的头结点head

2. 依次比较两个已排序链表结点L1、L2,加入新链表L中

3. 若L1结点已经全部合并到L中,但L2有剩余,则直接将L指针h指向L2后续结点;同理L2若还有剩余。

4. 返回head->next.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode 链表