LeetCode:2两数相加:给你两个非空的链表,表示两个非负的整数。它们每位数字都是按照逆序的方式存储的,并且每个节点只能存储一位数字。 请你将两个数相加,并以相同形式返回一个表示和的链表。

题目

给你两个非空的链表,表示两个非负的整数。它们每位数字都是按照逆序的方式存储的,并且每个节点只能存储一位数字。
请你将两个数相加,并以相同形式返回一个表示和的链表。
你可以假设除了数字 0 之外,这两个数都不会以 0 开头。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/add-two-numbers

题解

通过python类来实现链表的数据存储和关联,遍历两个存储数据的链表获取每个结点的数据并相加,如果有一个链表数据读取相较于另一个链表读完数据,则将以读完的链表节点以0代替

提交代码

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next

class Solution:
    def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
        carry = 0
        head = tail =None
        while (l1 != None) | (l2 != None):
            n1 = l1.val if l1 else 0
            n2 = l2.val if l2 else 0
            sum = n1 + n2 + carry
            if head == None:
                head = ListNode(sum % 10)
                tail = head
            else:
                tail.next = ListNode(sum % 10)
                tail = tail.next
            carry = sum // 10

            if l1:
                l1 = l1.next
            if l2:
                l2 = l2.next
                
        if carry > 0:
            tail.next = ListNode(carry)

        return head

扩展代码

# Definition for singly-linked list.
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

class SLinkedList:
    def __init__(self):
        self.head = None

    def addNode_begin(self,val):
        newNode = ListNode(val)
        newNode.next = self.head
        self.head = newNode

    def printList(self):
        printNode = self.head
        while printNode is not None:
            print(printNode.val)
            printNode = printNode.next 


class Solution:
    # def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
    def addTwoNumbers(self, l1: SLinkedList, l2: SLinkedList) -> ListNode:
        carry = 0
        head = None
        tail = None
        while (l1.head != None) | (l2.head != None):
            n1 = l1.head.val if l1.head else 0
            n2 = l2.head.val if l2.head else 0
            sum = n1 + n2 + carry
            if head == None:
                head = ListNode(sum % 10)  
                tail = head          
            else:
                tail.next = ListNode(sum % 10)
                tail = tail.next
            carry = sum // 10
            if l1.head:
                l1.head = l1.head.next
            if l2.head:
                l2.head = l2.head.next
        
        if carry > 0:
            tail.next = ListNode(carry)
        
        return head


if __name__ == "__main__":
    sol = Solution()
    list = SLinkedList()
    l2 = SLinkedList()
    # 示例1
    # list.head = ListNode(3)
    # list.addNode_begin(4)
    # list.addNode_begin(2)
    
    # l2.head = ListNode(4)
    # l2.addNode_begin(6)
    # l2.addNode_begin(5)
    # list.printList()
    # print("分割线-----------------------")
    # l2.printList() 


    # 示例2
    # list.head = ListNode(9)
    # list.addNode_begin(9)
    # list.addNode_begin(9)
    # list.addNode_begin(9)
    # list.addNode_begin(9)
    # list.addNode_begin(9)
    # list.addNode_begin(9)

    # l2.head = ListNode(9)
    # l2.addNode_begin(9)
    # l2.addNode_begin(9)
    # l2.addNode_begin(9)   


    # 示例3
    # list.head = ListNode(0)
    # l2.head = ListNode(0)


    print("l1 + l2 result:")
    l3 = sol.addTwoNumbers(list,l2)
    while l3 is not None:
        print(l3.val)
        l3 = l3.next


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
```cpp #include <iostream> using namespace std; struct ListNode { int val; ListNode* next; ListNode() : val(0), next(nullptr) {} ListNode(int x) : val(x), next(nullptr) {} ListNode(int x, ListNode* next) : val(x), next(next) {} }; ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { ListNode* dummy = new ListNode(0); ListNode* curr = dummy; int carry = 0; while (l1 != nullptr || l2 != nullptr) { int x = (l1 != nullptr) ? l1->val : 0; int y = (l2 != nullptr) ? l2->val : 0; int sum = x + y + carry; carry = sum / 10; curr->next = new ListNode(sum % 10); curr = curr->next; if (l1 != nullptr) { l1 = l1->next; } if (l2 != nullptr) { l2 = l2->next; } } if (carry > 0) { curr->next = new ListNode(carry); } return dummy->next; } int main() { // 创建链表 l1: 2 -> 4 -> 3 ListNode* l1 = new ListNode(2); l1->next = new ListNode(4); l1->next->next = new ListNode(3); // 创建链表 l2: 5 -> 6 -> 4 ListNode* l2 = new ListNode(5); l2->next = new ListNode(6); l2->next->next = new ListNode(4); // 调用函数进行相加 ListNode* result = addTwoNumbers(l1, l2); // 输出结果链表 while (result != nullptr) { cout << result->val << " "; result = result->next; } return 0; } ``` 这段C++代码实现了将两个逆序存储非负整数链表相加并以相同形式返回一个表示和的链表。首先,我们定义了一个`ListNode`结构体来表示链表节点。然后,我们实现了`addTwoNumbers`函数来进行链表相加的操作。在函数中,我们使用了一个`dummy`节点作为结果链表的头节点,并使用一个`curr`指针来指向当前节点。我们还定义了一个`carry`变量来保存进位值。在循环中,我们依次遍历两个链表节点,并将对应位置的数字相加,再加上进位值。然后,我们将相加结果的个位数作为新节点的值,并更新进位值。最后,如果还有进位值,我们在结果链表的末尾添加一个节点。最后,我们返回结果链表的头节点。 以上是一种C++实现的方式,你可以根据需要进行调整和修改。 #### 引用[.reference_title] - *1* [它们每位数字都是按照 逆序方式存储的,并且每个节点只能存储 一位 数字你将两个相加并以相同...](https://blog.csdn.net/m0_56183819/article/details/124357484)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [Leetcode 2.两数相加 两个非空链表表示两个非负整数。它们每位数字都是按照逆序方式存储的。](https://blog.csdn.net/qfxl0724/article/details/126048497)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [它们每位数字都是按照 逆序方式存储的,并且每个节点只能存储 一位 数字你将两个相加并以相同...](https://blog.csdn.net/m0_50672338/article/details/127810149)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值