1. 两数相加

题目描述:给定两个非空链表来表示两个非负整数,位数按照逆序方式存储,并且每个节点只能存储一位数字。求这两个数相加起来的结果,并以相同形式返回一个表示和的链表。

例如,输入的链表 1->2->3 和 4->5->6,输出的结果为 5->7->9。

解题思路:

这道题可以用简单的模拟法来解决。由于链表中数字按照逆序的方式存储,我们可以使用两个指针分别遍历两个链表,同时维护一个进位的变量carry,将两个节点的值以及进位相加,得到新的节点值,然后更新进位的值,并将新节点加入到答案链表中。

需要注意的是,当两个链表长度不同时,遍历链表时较短的链表后面缺失的节点视为0,保证两个链表能够全部遍历到。

Java代码:
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    ListNode dummy = new ListNode(0);
    ListNode cur = dummy;
    int carry = 0;
    while (l1 != null || l2 != null) {
        int x = (l1 != null) ? l1.val : 0;
        int y = (l2 != null) ? l2.val : 0;
        int sum = carry + x + y;
        carry = sum / 10;
        cur.next = new ListNode(sum % 10);
        cur = cur.next;
        if (l1 != null) l1 = l1.next;
        if (l2 != null) l2 = l2.next;
    }
    if (carry > 0) {
        cur.next = new ListNode(carry);
    }
    return dummy.next;
}

Python代码:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
    dummy = ListNode(0)
    cur = dummy
    carry = 0
    while l1 or l2:
        x = l1.val if l1 else 0
        y = l2.val if l2 else 0
        sum = carry + x + y
        carry = sum // 10
        cur.next = ListNode(sum % 10)
        cur = cur.next
        if l1: l1 = l1.next
        if l2: l2 = l2.next
    if carry > 0:
        cur.next = ListNode(carry)
    return dummy.next


C语言代码:
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2){
    struct ListNode *dummy = (struct ListNode *)malloc(sizeof(struct ListNode));
    struct ListNode *cur = dummy;
    int carry = 0;
    while (l1 || l2) {
        int x = (l1) ? l1->val : 0;
        int y = (l2) ? l2->val : 0;
        int sum = carry + x + y;
        carry = sum / 10;
        cur->next = (struct ListNode*)malloc(sizeof(struct ListNode));
        cur->next->val = sum % 10;
        cur = cur->next;
        if (l1) l1 = l1->next;
        if (l2) l2 = l2->next;
    }
    if (carry > 0) {
        cur->next = (struct ListNode*)malloc(sizeof(struct ListNode));
        cur->next->val = carry;
        cur = cur->next;
    }
    cur->next = NULL;
    return dummy->next;
}


以上三份代码时间复杂度均为O(max(m, n)),其中m和n分别是两个链表的长度。由于这个问题能够用简单的模拟法解决,因此在大多数情况下此方法已经足够高效。

以上文章内容均由ChatGPT3.5版本给出的作答,有问题可以提出来一起探讨!

Logo

GitCode 天启AI是一款由 GitCode 团队打造的智能助手,基于先进的LLM(大语言模型)与多智能体 Agent 技术构建,致力于为用户提供高效、智能、多模态的创作与开发支持。它不仅支持自然语言对话,还具备处理文件、生成 PPT、撰写分析报告、开发 Web 应用等多项能力,真正做到“一句话,让 Al帮你完成复杂任务”。

更多推荐