classSolution { public: ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) { intcarryBit = 0; ListNode tmpHead(0), *res = &tmpHead; while(l1 && l2) { l1->val += (l2->val + carryBit); carryBit = l1->val / 10; l1->val %= 10; res->next = l1; res = l1; l1 = l1-...
publicclassSolution { publicListNode addTwoNumbers(ListNode l1, ListNode l2) { //如果给出就为空,则直接返回另外一个链表 if(l1 ==null)returnl2; if(l2 ==null)returnl1; intflag =0;//存放进位信息,但是并不是处理最后的进位标志 //构造返回结果的第一个节点 ListNode result =newListNode((l1.val ...
# class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]: # 哨兵结点,方便后续处理 head_pre = ListNode(0) # 结果链表的尾结点,方便...
} Solution s=newSolution(); tmp=s.addTwoNumbers(node1, node2);while(tmp !=null) { System.out.format("%d ", tmp.val); tmp=tmp.next; } }publicListNode addTwoNumbers(ListNode l1, ListNode l2) { ListNode head=newListNode(0); ListNode cur_node=head;intcarry = 0;while(l1 !=null||...
classSolution{public:ListNode*addTwoNumbers(ListNode*l1,ListNode*l2){ListNode*ret=newListNode();ListNode*pnt=ret;bool carry=false;while(l1!=nullptr||l2!=nullptr||carry){int cur=0;if(l1!=nullptr){cur+=l1->val;l1=l1->next;}if(l2!=nullptr){cur+=l2->val;l2=l2->next;}if(carry){cur...
publicstaticListNodeaddTwoNumbers(ListNode l1,ListNode l2){// 边界条件判断if(l1==null){returnl2;}elseif(l2==null){returnl1;}ListNode head=newListNode(0);ListNode point=head;int carry=0;while(l1!=null&&l2!=null){int sum=carry+l1.val+l2.val;ListNode rest=newListNode(sum%10);point.next...
class Solution: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: link1 = l1 link2 = l2 while(link1!=None and link2 !=None): a = link1.val link2.val += a link1.val = link2.val link1 = link1.next
1classSolution {2public:3ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {4ListNode *res =newListNode(-1);5ListNode *cur =res;6intcarry =0;7while(l1 ||l2) {8intn1 = l1 ? l1->val :0;9intn2 = l2 ? l2->val :0;10intsum = n1 + n2 +carry;11carry = sum /10;12cur-...
3 输入与输出:/*** Definition for singly-linked list.* struct ListNode {* int val;* ListNode *next;* ListNode(int x) : val(x), next(NULL) {}* };*/class Solution {public: ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { }};4 解决思路:从表头开始相加,记录每次相加...
LeetCode 2. Add Two Numbers non-empty You may assume the two numbers do not contain any leading zero, except the number 0 itself. Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: answer: class Solution { public: ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {...