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.

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: 7 -> 0 -> 8

思路:

这一篇只知道大致思路,将链表l1 l2分别反转,然后分别将值赋给数字,之后数字相加,将数字再转换成链表,最后再把链表反转。

但是对于如何将链表反转,如何将链表值赋给数字,完全没思路,所以直接看了解析。

标准答案:

 1 public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
 2     ListNode dummyHead = new ListNode(0);//先自己定义一个头节点的名字dummyHead为0个节点,这样就方便描述
 3     ListNode p = l1, q = l2, curr = dummyHead;//p,q分别初始化为链表l1和l2的头,curr代表当前相加结果的个位
 4     int carry = 0;//表示进位
 5     while (p != null || q != null) {//只要p和q到达不了末尾的空,就一直循环
 6         int x = (p != null) ? p.val : 0;//要是p不等于空,则将p当前的值赋给x(要是为空,代表走到链表末尾了,赋值给x为0)
 7         int y = (q != null) ? q.val : 0;//同理,q节点的值给y
 8         int sum = carry + x + y;//将x+y+进位的值相加,得到sum.
 9         carry = sum / 10;//sum/10得到的整数即为进位
10         curr.next = new ListNode(sum % 10);//curr为新定义的链表,一开始只定义了一个头,现在将头.next填充:sum%10的余数
11         curr = curr.next;//curr往后移一位,p和q只要没到链表尾也后移一位
12         if (p != null) p = p.next;
13         if (q != null) q = q.next;
14     }
15     if (carry > 0) { //最后的若carry还大于0,即还要进位,那么再创建一个节点。
16         curr.next = new ListNode(carry);
17     }
18     return dummyHead.next;//返回链表头.next
19 }

标准解题思路:

题目可以如图理解,然后将807再反转,则为7->0->8.

具体分析写在代码注释中了。

 

转载于:https://www.cnblogs.com/kangkang-xiaoguai/p/6822790.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值