我们遍历两个linked lists,把它们每个结点的值进行相加,并加上之前一组求和得到的carry。然后更新carry,current,和已经获取的linked lists。 最后,返回dummy结点的next结点,就是结果linked list里面的头(结点)。
Add Two Numbers You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. Input:(2 -> 4 -> 3) + (5 -> 6 -> 4) Output:7 ->...
publicclassSolution{publicListNodeaddLists(ListNodel1,ListNodel2){if(l1==null&&l2==null){returnnull;}ListNodehead=newListNode(0);ListNodepoint=head;intcarry=0;while(l1!=null&&l2!=null){intsum=carry+l1.val+l2.val;point.next=newListNode(sum%10);carry=sum/10;l1=l1.next;l2=l2.next;point=...
3LinkedList<Integer>l2) {4LinkedList<Integer> l3 =newLinkedList<Integer>();5if(l1.isEmpty())6returnl2;7if(l2.isEmpty())8returnl1;9intcarry = 0;10while(!l1.isEmpty() && !l2.isEmpty()) {11intsum = 0;12sum = (l1.peek() + l2.peek() + carry) % 10;13carry = (l1.poll(...
Figure 2-2 这样,list里的每一位数都储存在link lists里了,增加的linked lists的长度就是list的长度。这里dummy root是构造linked lists常用的一种形式,将dummy root作为一个参照,每次指向下一个node从而按要求构造好linked lists, 而dummy node就相当于构造的链表的头结点。
```cpp/*** Definition for singly-linked list.* 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) {}* };*/classSolution{public:ListNode*...
Leetcode 算法 - 2. Add Two Numbers Posted August 16, 2016 问题链接:2. Add Two Numbers问题描述: You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it...
2. Add Two Numbers You are given twonon-emptylinked lists representing two non-negative integers. The digits are stored inreverse orderand each of their nodes contain a single digit. Add the two numbers and return it as a linked list. ...
2. Add Two Numbers(链表尾插法) You are given twonon-emptylinked lists representing two non-negative integers. The digits are stored inreverse orderand each of their nodes contain a single digit. Add the two numbers and return it as a linked list....
LeetCode: 2. Add Two Numbers LeetCode: 2. Add Two Numbers 题目描述 You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list...