zoukankan      html  css  js  c++  java
  • [LeetCode] Merge Two Sorted Lists

    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) {
            // IMPORTANT: Please reset any member data you declared, as
            // the same Solution instance will be reused for each test case.
            if(l1 == NULL && l2 == NULL)
                return NULL;
            if(l1 == NULL)
                return l2;
            if(l2 == NULL)
                return l1;
            
            ListNode *root, *last, *t_l1 = l1, *t_l2 = l2;
            if(t_l1 -> val < t_l2 -> val)
            {
                root = t_l1;
                last = t_l1;
                t_l1 = t_l1 -> next;
            }
            else
            {
                root = t_l2;
                last = t_l2;
                t_l2 = t_l2 -> next;
            }
            
            while(true)
            {
                if(t_l1 == NULL)
                {
                    if(t_l2 == NULL)
                    {
                        break;   
                    }
                    else
                    {
                        last -> next = t_l2;
                        break;
                    }
                }
                else
                {
                    if(t_l2 == NULL)
                    {
                        last -> next = t_l1;
                        break;
                    }
                    else
                    {
                        if(t_l1 -> val < t_l2 -> val)
                        {
                            last -> next = t_l1;
                            last = t_l1;
                            t_l1 = t_l1 -> next;
                        }
                        else
                        {
                            last -> next = t_l2;
                            last = t_l2;
                            t_l2 = t_l2 -> next;
                        }
                    }
                }
            }
            
            return root;
        }
    };
  • 相关阅读:
    USACO 1.2 Broken Necklace
    USACO 1.2 Friday the Thirteenth
    USACO 1.1 Greedy Gift Givers
    USACO 1.1 Your Ride Is Here
    CSP考试策略
    CF444A DZY Loves Physics【结论】
    树状数组-复习笔记
    CF792E Colored Balls【思维】
    USACO4.4 Shuttle Puzzle【bfs+优化】
    拓扑排序-学习笔记
  • 原文地址:https://www.cnblogs.com/changchengxiao/p/3416682.html
Copyright © 2011-2022 走看看