leetcode刷题——2. Add Two Numbers

被ListNode的结构玩儿死了,还是不够熟悉,怪自己

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.

Example

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
   ListNode list = new ListNode(0);
        ListNode q = list;
        int sum;
        boolean plus=false;
        while(l1!=null||l2!=null){
            sum=0;
            if(plus==true){
                sum+=1;
                plus=false;
            }
            if(l1!=null){
                sum+=l1.val;
                l1=l1.next;
            }
            if(l2!=null){
                sum+=l2.val;
                l2=l2.next;
            }
            if(sum>9){
                plus=true;
                q.next=new ListNode(sum%10);
            }else{
                plus=false;
                q.next=new ListNode(sum%10);
            }
            q=q.next;
            
        }
        if(plus==true){
            q.next=new ListNode(1);
            q=q.next;
        }
        return list.next;
    }
}


在里面其实有挺多坑的

1.在调用.next的时候,应该先确认这个节点是否有下一个节点

2.之前一直尝试着:ListNode result=new ListNode(0);(全局)

ListNode q=new ListNode(...)(局部),result=q;

现在已经搞不明白当时思路了:

扫描二维码关注公众号,回复: 157272 查看本文章

     而正确思路应该是:首先建立一个返回的节点,再建立一个临时节点变量,使得这个变量指向返回节点,然后对这个变量赋值下一个节点,等等

3.题目中说明了不用返回以0值开头的节点,一开始在想这怎么实现,其实很简单:先创建一个0值的头结点,在最后返回的时候,返回头结点的next下一个节点

猜你喜欢

转载自blog.csdn.net/u013177799/article/details/80167271