有空就看看的leetcode7——合并两个有序链表(c++版)

有空就看看的leetcode7——合并两个有序链表(c++版)

学习前言

考试好难啊。
在这里插入图片描述

题目

将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。

示例:

输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4

解法

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

思路:
对两个链表从头开始比较,那个小就把那个数取出来放到新链表里面,如果某个链表空了,直接操作另一个链表就可以了

发布了167 篇原创文章 · 获赞 112 · 访问量 24万+

猜你喜欢

转载自blog.csdn.net/weixin_44791964/article/details/103812902