* (leetcode )Merge Two Sorted Lists

来源:互联网 发布:暗物质与灵魂 知乎 编辑:程序博客网 时间:2024/06/07 12:41

Merge Two Sorted Lists

 Total Accepted: 27201 Total Submissions: 81656My Submissions

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.


/** * 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) {        ListNode *list = new ListNode(0);        list->next = NULL;        ListNode *tail = list;                while(NULL!=l1&&NULL!=l2){            if(l1->val<l2->val){                tail->next = l1;                tail = l1;                l1 = l1->next;            }            else{                tail->next = l2;                tail = l2;                l2 = l2->next;            }                        }        if(NULL!=l1)            tail->next = l1;        if(NULL!=l2)            tail->next = l2;        //free(tail); //tail又没有new出来,根本用不着free!!        l1 = list->next;        free(list);//将new的list free        return l1;    }};


0 0
原创粉丝点击