LeetCode : Add Two Numbers [java]

来源:互联网 发布:win读取mac硬盘软件 编辑:程序博客网 时间:2024/05/01 21:27

You are given two linked lists representing two non-negative numbers. 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.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)

Output: 7 -> 0 -> 8

思路:按链表顺序,依次相加,进位进到下一个节点元素,最后有进位的,追加一个节点元素。

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { val = x; } * } */public class Solution {        public ListNode addTwoNumbers(ListNode l1, ListNode l2) {        int over = 0;int num1 = 0;int num2 = 0;ListNode head = new ListNode(0);ListNode p = head;while (l1 != null || l2 != null) {if (l1 != null) {num1 = l1.val;l1 = l1.next;}if (l2 != null) {num2 = l2.val;l2 = l2.next;}int sum = num1 + num2 + over;over = sum / 10;ListNode node = new ListNode(sum % 10);p.next = node;p = p.next;num1 = 0;num2 = 0;}if (over != 0) {ListNode node = new ListNode(over);p.next = node;}return head.next;    }}


1 0
原创粉丝点击