[蓝蓝计算机考研算法二期]-day15

97 阅读1分钟

21、合并两个有序链表

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

示例 1:

image.png

输入:l1 = [1,2,4], l2 = [1,3,4] 输出:[1,1,2,3,4,4]

示例 2:

输入:l1 = [], l2 = [] 输出:[]

示例 3:

输入:l1 = [], l2 = [0] 输出:[0]

思路

利用链表有序的思路,同时遍历两个链表,当list1val小于list2val时,将list1的当前值加入新链表的链尾,反之则将list2的当前值加入新链表的链尾。

具体实现

# include<stdio.h>
# include<stdlib.h>

// 链表结构体
struct ListNode {
    int val;
    struct ListNode* next;
};

// 创建链表的函数
struct ListNode* createList() {
    int val;
    printf("请输入链表元素的值(输入-1结束):\n");
    scanf("%d", &val);
    
    struct ListNode* head = NULL;
    struct ListNode* current = NULL;
    
    while (val != -1) {
        struct ListNode* node = (struct ListNode*)malloc(sizeof(struct ListNode));
        node->val = val;
        node->next = NULL;
        
        if (head == NULL) {
            head = node;
            current = node;
        } else {
            current->next = node;
            current = node;
        }
        
        scanf("%d", &val);
    }
    
    return head;
}

// 合并链表的函数
struct ListNode* mergeList(struct ListNode* list1, struct ListNode* list2) {
	struct ListNode *head, *p, *q;
    head = (struct ListNode*)malloc(sizeof(struct ListNode));
    head->next = NULL;
    q = head;

    while (list1 != NULL && list2 != NULL) {
        if (list1->val < list2->val) {
            p = (struct ListNode*)malloc(sizeof(struct ListNode));
            p->val = list1->val;
            p->next = NULL;
            q->next = p;
            q = p;
            list1 = list1->next;
        } else {
            p = (struct ListNode*)malloc(sizeof(struct ListNode));
            p->val = list2->val;
            p->next = NULL;
            q->next = p;
            q = p;
            list2 = list2->next;
        }
    }

    if (list1 != NULL) {
        q->next = list1;
    }

    if (list2 != NULL) {
        q->next = list2;
    }

    return head->next;
} 

// 打印链表的函数
void printList(struct ListNode* head) {
    struct ListNode* current = head;
    while (current != NULL) {
        printf("%d ", current->val);
        current = current->next;
    }
    printf("\n");
}


int main() {
	struct ListNode* list1 = createList();
	struct ListNode* list2 = createList();
    
    struct ListNode* result = mergeList(list1, list2);
    
    printf("合并后的链表:"); 
    printList(result);
	
	return 0;
} 

image.png

小结

本次算法依然是对链表的使用,因为链表有序所以可以降低设计算法的难度,在读题时要多注意。