[剑指 Offer 25]合并两个排序的链表

92 阅读1分钟

[剑指 Offer 25]合并两个排序的链表

方法1: 递归方法

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
#include"stdio.h"
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2){
    if(l1 == NULL){
        return l2;
    }

    if(l2 == NULL){
        return l1;
    }

    struct ListNode* head;
    if(l1->val <= l2->val){
        head = l1;
        head->next = mergeTwoLists(l1->next, l2);
    } else {
        head = l2;
        head->next = mergeTwoLists(l1, l2->next);
    }

    return head;
}

方法2: 循环方法

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
#include"stdio.h"
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2){
    struct ListNode head;
    struct ListNode* currNode = &head;
    while (l1 != NULL && l2 != NULL){
        if(l1->val <= l2->val){
            currNode->next = l1;
            l1 = l1->next;
        } else {
            currNode->next = l2;
            l2 = l2->next;
        }

        currNode = currNode->next;
    }

    if(l1 != NULL){
        currNode->next = l1;
    } else {
        currNode->next = l2;
    }

    return head.next;
}
  • 使用dummy实体head节点可以很方便的处理边界情况.
  • 解决问题时优先使用递归思路去解决,先跑通再优化.
  • 循环可以减少函数调用栈的深度,递归实现之后一定要尝试着向着循环做优化.
  • 此循环解法又可称之为双指针解法,第一个指针指dummy节点,第二个指针指curr指针,起到串联作用.
  • 当两条链表一条可能为NULL的情况不好处理的时候,尝试着将if判断后挪.