美文网首页
21. Merge Two Sorted Lists

21. Merge Two Sorted Lists

作者: Al73r | 来源:发表于2017-09-27 10:23 被阅读0次

    题目

    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 *ans, *pa;
            if(l1==NULL) return l2;
            if(l2==NULL) return l1;
            if(l1->val < l2->val){
                ans = l1;
                l1 = l1->next;
            }
            else{
                ans = l2;
                l2 = l2->next;
            }
            pa=ans;
            while(l1!=NULL && l2!=NULL){
                if(l1->val < l2->val){
                    pa->next = l1;
                    l1=l1->next;
                    pa=pa->next;
                }
                else{
                    pa->next = l2;
                    l2=l2->next;
                    pa=pa->next;
                }
            }
            while(l1!=NULL){
                pa->next = l1;
                l1=l1->next;
                pa=pa->next;
            }
            while(l2!=NULL){
                pa->next = l2;
                l2=l2->next;
                pa=pa->next;
            }
            return ans;
        }
    };
    

    思考

    重新理了下对于链表的理解。好久不用还是会生疏啊。

    相关文章

      网友评论

          本文标题:21. Merge Two Sorted Lists

          本文链接:https://www.haomeiwen.com/subject/ifbyextx.html