力扣第二题

给你两个 非空 的链表,表示两个非负的整数。它们每位数字都是按照 逆序 的方式存储的,并且每个节点只能存储 一位 数字。请你将两个数相加,并以相同形式返回一个表示和的链表。你可以假设除了数字 0 之外,这两个数都不会以 0 开头。

  • 输入:l1 = [2,4,3], l2 = [5,6,4]
  • 输出:[7,0,8]
  • 解释:342 + 465 = 807.
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;
	}

	@Override
	public String toString() {
		return "ListNode [val=" + val + ", next=" + next + "]";
	}
}
public class Test03 {
	
	public static void main(String[] args) {
		ListNode l1 = new ListNode();
		l1.val = 2;
		ListNode l11 = new ListNode();
		l11.val = 4;
		ListNode l111 = new ListNode();
		l111.val = 3;
		l1.next = l11;
		l11.next = l111;
		System.out.println(l1.toString());
		
		ListNode l2 = new ListNode();
		l2.val = 9;
		ListNode l22 = new ListNode();
		l22.val = 6;
		ListNode l222 = new ListNode();
		l222.val = 4;
		l2.next = l22;
		l22.next = l222;
		System.out.println(l2.toString());
		
		System.out.println(addTwoNumbers(l1,l2));
	}
	
	//  2   4   3
	//  9   6   4
	//  1   1   8
	public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode p1 = l1, p2 = l2;
        //定义一个虚拟节点dummy
        ListNode dummy = new ListNode(-1);
        //p节点指向dummy节点
        ListNode p = dummy;
        //定义两个临时变量
        int carry = 0, newVal = 0;
        while (p1 != null || p2 != null || carry > 0) {
        	//把p1,p2的val加起来,最开始肯定指向的是第一位
            newVal = (p1 == null ? 0: p1.val) + (p2 == null ? 0: p2.val) + carry; 
            //把newVal取商,newVal < 10的话,取0,new>10的话,取1
            carry = newVal / 10;
            //把newVal取模,newVal < 10的话,取newVal,new>10的话,取1,
            newVal %= 10;
            //p节点的下一个节点指向一个新节点
            p.next = new ListNode(newVal);
            //p1和p2往后移
            p1 = p1 == null? null: p1.next;
            p2 = p2 == null? null: p2.next;
            //p节点也向后移
            p = p.next;
        }
        //返回该虚拟节点
        return dummy.next;
    }
}
posted @ 2022-01-04 19:12  卡卡罗特琪琪  阅读(44)  评论(0编辑  收藏  举报