leetcode 两数相加 java
一开始没看懂题目,没明白逆序是啥意思,原来就是从右向左看链表。
返回链表的时候,只需要返回链表的头节点即可,即返回了整个链表。
算法和代码都可以参考这篇博客,只不过这个是c++版本的
https://xas-sunny.blog.csdn.net/article/details/140059170
/*** Definition for singly-linked list.* public class ListNode {* int val;* ListNode next;* ListNode() {}* ListNode(int val) { this.val = val; }* ListNode(int val, ListNode next) { this.val = val; this.next = next; }* }*/
class Solution {public ListNode addTwoNumbers(ListNode l1, ListNode l2) {//定义哨兵位节点,用来指向头指针,返回结果ListNode pre = new ListNode(-1);//指向上述哨兵位节点,作为当前节点ListNode cur = pre;//定义一个可移动的指针,用来指向存储两个数之和的位置int rise = 0;while(l1!=null || l2 !=null){int x = l1==null ? 0 : l1.val;int y = l2==null ? 0 : l2.val;int sum = x+y+rise;rise = sum/10;sum=sum%10;//rise=sum/10;//将求和数赋值给新链表的节点,//注意这个时候不能直接将sum赋值给cur.next = sum。这时候会报,类型不匹配。//所以这个时候要创一个新的节点,将值赋予节点cur.next = new ListNode(sum);cur = cur.next;if(l1!=null){l1=l1.next;}if(l2!=null){l2=l2.next;}//如果有进位,那么将进位数,赋予链表的新节点if(rise==1){cur.next = new ListNode(rise);}}return pre.next;}
}