> 文章列表 > 合并链表相关的练习

合并链表相关的练习

合并链表相关的练习

目录

一、合并两个有序链表

二、两数相加



一、合并两个有序链表

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

示例 1

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

输出:[1,1,2,3,4,4]

示例 2

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

输出:[]

示例 3

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

输出:[0]

提示

  • 两个链表的节点数目范围是 [0, 50]

  • -100 <= Node.val <= 100

  • l1l2 均按 非递减顺序 排列

代码实现一(不设置哨兵位的头结点)

struct ListNode* mergeTwoLists(struct ListNode* list1, struct ListNode* list2)
{if (list1 == NULL)return list2;else if (list2 == NULL)return list1;
​struct ListNode* newhead = NULL;struct ListNode* tail = NULL;struct ListNode* cur1 = list1;struct ListNode* cur2 = list2;while (cur1 && cur2){if (cur1->val < cur2->val){if (newhead == NULL){newhead = tail = cur1;}else{tail->next = cur1;tail = cur1;}cur1 = cur1->next;}else{if (newhead == NULL){newhead = tail = cur2;}else{tail->next = cur2;tail = cur2;}cur2 = cur2->next;}}if (cur1){tail->next = cur1;}if (cur2){tail->next = cur2;}return newhead;
}

代码实现二(设置哨兵位的头结点)

struct ListNode* mergeTwoLists(struct ListNode* list1, struct ListNode* list2)
{struct ListNode* guard = (struct ListNode*)malloc(sizeof(struct ListNode));guard->next = NULL;struct ListNode* tail = guard;struct ListNode* cur1 = list1;struct ListNode* cur2 = list2;while (cur1 && cur2){if (cur1->val < cur2->val){tail->next = cur1;tail = cur1;cur1 = cur1->next;}else{tail->next = cur2;tail = cur2;cur2 = cur2->next;}}if (cur1){tail->next = cur1;}if (cur2){tail->next = cur2;}struct ListNode* head = guard->next;free(guard);return head; 
}

二、两数相加

给你两个 非空 的链表,表示两个非负的整数。它们每位数字都是按照 逆序 的方式存储的,并且每个节点只能存储 一位 数字。

请你将两个数相加,并以相同形式返回一个表示和的链表。

你可以假设除了数字 0 之外,这两个数都不会以 0 开头。

示例 1

输入:l1 = [2,4,3], l2 = [5,6,4]

输出:[7,0,8]

解释:342 + 465 = 807. 

示例 2

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

输出:[0]

示例 3

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

输出:[8,9,9,9,0,0,0,1]

提示

  • 每个链表中的节点数在范围 [1, 100]

  • 0 <= Node.val <= 9

  • 题目数据保证列表表示的数字不含前导零

代码实现

struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2)
{struct ListNode* guard = (struct ListNode*)malloc(sizeof(struct ListNode));guard->next = NULL;struct ListNode* tail = guard;// 两数相加int sum = 0;while (l1 || l2 || sum){if (l1 != NULL){sum += l1->val;l1 = l1->next;}if (l2 != NULL){sum += l2->val;l2 = l2->next;}// 生成一个新结点struct ListNode* newnode = (struct ListNode*)malloc(sizeof(struct ListNode));newnode->val = sum % 10;  // newnode->val 设置为 sum 的个位newnode->next = NULL;// 尾插tail->next = newnode;tail = newnode;  // 或者写成 tail = tail->next;// 更新 sumsum /= 10;  // sum 更新为原来 sum 的十位}struct ListNode* head = guard->next;free(guard);return head;
}