首页 > 其他 > 详细

Merge Two Sorted Lists

时间:2015-03-13 22:01:59      阅读:281      评论:0      收藏:0      [点我收藏+]

两个指针的做法,但比起2个数组有序的数组的话,链表做更容易,因为当一个链表遍历结束后,tail指针并不需要遍历另一个链表,只要直接指向它就行

 

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode *mergeTwoLists(struct ListNode *l1, struct ListNode *l2) {
    struct ListNode *head = (struct ListNode *)malloc(sizeof(struct ListNode));
    struct ListNode *tail = head;
    while(l1&&l2){
        if(l1->val<l2->val){
            tail->next = l1;
            l1 = l1->next;
        }else {
            tail->next = l2;
            l2 = l2->next;
        }
        tail = tail->next;
    }
    //很傻比的后面全部遍历一遍
    while(l1){
        tail->next = l1;
        l1 = l1->next;
        tail = tail->next;
    }
    while(l2){
        tail->next = l2;
        l2 = l2->next;
        tail = tail->next;
    }
    return head->next;
}
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode *mergeTwoLists(struct ListNode *l1, struct ListNode *l2) {
    struct ListNode *head = (struct ListNode *)malloc(sizeof(struct ListNode));
    struct ListNode *tail = head;
    while(l1&&l2){
        if(l1->val<l2->val){
            tail->next = l1;
            l1 = l1->next;
        }else {
            tail->next = l2;
            l2 = l2->next;
        }
        tail = tail->next;
    }
    if(!l1)tail->next = l2;
    else if(!l2) tail->next = l1;
    return head->next;
}

 

Merge Two Sorted Lists

原文:http://www.cnblogs.com/llei1573/p/4335972.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!