【leetcode】21-MergeTwoSortedLists

problem

MergeTwoSortedLists

一种方法是迭代,一种方法是递归;

code

/**
 * 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(INT_MIN);//
        ListNode* out = &head;
        while(l1&&l2)//
        {
            if(l1->val < l2->val) { out->next = l1; l1 = l1->next;}
            else {out->next = l2; l2 = l2->next; }
            out = out->next;//
        }
        out->next = l1 ? l1 : l2;//
        return head.next;//
    }
};
View Code

 将两个有序的链表合并为一个有序链表;

主要考察单向链表的基本用法;

头结点;

两个链表都有数值的时候才进行比较;

注意比较之后更新每个链表的头结点;

注意判断空链表时如何处理;

注意返回的是头结点的next;

参考

1.leetcode-MergeTwoSortedLists;

原文地址:https://www.cnblogs.com/happyamyhope/p/9934467.html