Can you solve this real interview question? Add Two Numbers II - You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contains a single digit. Add the two numbers
*/classSolution{publicListNodeaddTwoNumbers(ListNode l1, ListNode l2){if(l1==null)returnl2;if(l2==null)returnl1; ListNode head=newListNode(-1); ListNode cur=head;intcarry=0;//进位while(l1!=null|| l2!=null){intnum1=l1==null?0:l1.val;intnum2=l2==null?0:l2.val;intsum=num1+num2...
tmp=node2;for(inti = 1; i < data2.length; i ++) { tmp.next=newListNode(data2[i]); tmp=tmp.next; } Solution s=newSolution(); tmp=s.addTwoNumbers(node1, node2);while(tmp !=null) { System.out.format("%d ", tmp.val); tmp=tmp.next; } }publicListNode addTwoNumbers(ListNode...
class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { //初始化为0的节点 ListNode init = new ListNode(0); //当前输出节点位置,初始化为initListNode ListNode current = init; //进位值 int carry = 0; while (l1 != null || l2 != null) { ...
public class Solution { /* * 方法1 */ public static ListNode addTwoNumbers(ListNode l1,ListNode l2) { //如果都为空 直接返回不为空的一个参数 如果都未空 则返回空 if(l1 == null || l2 == null){ return l1 == null ?(l2 == null ?null:l2):l1; ...
博客园:https://www.cnblogs.com/grandyang/p/4129891.htmlGitHub:https://github.com/grandyang/leetcode/issues/2个人网页:https://grandyang.com/leetcode/2/, 视频播放量 103、弹幕量 0、点赞数 0、投硬币枚数 0、收藏人数 1、转发人数 0, 视频作者 Grandyang刷尽天
212023-10 7 [LeetCode] 4. 寻找两个正序数组的中位数 272023-10 8 [LeetCode] 3. 无重复字符的最长子串 222023-10 9 [LeetCode] 2. Add Two Numbers 两个数字相加 312023-10 10 [LeetCode] 1. Two Sum 两数之和 482023-10 查看更多 猜你喜欢 4910 算法|Leetcode真题解析 by:幻梦成风 ...
val=0, next=None): # self.val = val # self.next = 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....
Leetcode c++ 方法/步骤 1 问题描述:您将获得两个非空链表,表示两个非负整数。 数字以相反的顺序存储,每个节点包含一个数字。 添加两个数字并将其作为链接列表返回。您可以假设这两个数字不包含任何前导零,除了数字0本身。2 问题示例:输入:(2 - > 4 - > 3)+(5 - > 6 - > 4)输出:7 - >...
# 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) # 结果链表的尾结点,方便...