LeetCode | 21. Merge Two Sorted Lists

来源:互联网 发布:淘宝3个月没卖出一件 编辑:程序博客网 时间:2024/05/17 02:37

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.
合并两个有序链表.好久没有使用指针,对指针明显不太熟练了.所以看起来非常简单的题目,调试了好久,一直有指针相关错误.而且只能光靠眼睛看,不方便本地调试,sigh.

/** * 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 == NULL)             return l2;        if(l2 == NULL)            return l1;        ListNode* head = NULL;        if(l1->val <= l2->val)//确定首地址        {            head = l1; l1 = l1->next;        }        else        {            head = l2; l2 = l2->next;        }        ListNode* it = head;        while(l1!=NULL && l2!=NULL)        {            if(l1->val <= l2->val)            {                it->next = l1;                l1 = l1->next;            }            else            {                it->next = l2;                l2 = l2->next;            }            it = it->next;        }        if(l1)            it->next = l1;        if(l2)            it->next = l2;        return head;    }};
1 0
原创粉丝点击