zoukankan      html  css  js  c++  java
  • 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.

    if... else if不要偷懒直接写 if...if...

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

      

  • 相关阅读:
    问题 F: A+B和C (15)
    问题 E: Shortest Distance (20)
    完数
    分解质因数
    念整数
    问题 B: 习题7-7 复制字符串中的元音字母
    问题 A: 习题7-5 字符串逆序存放
    问题 D: 习题6-12 解密
    计算机的重点编码方式
    PyCharm更换第三方包源
  • 原文地址:https://www.cnblogs.com/pengyu2003/p/3572425.html
Copyright © 2011-2022 走看看