LeetCode | Add Two Numbers

 

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; }
 * }
 */

 

 //整理思路与昨天的add binary非常类似,程序结构也一样
 //注意此处list是倒序存储数字的,即低位在左,高位在右
 //故只需要正向遍历相加,并维护进位即可
public class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
	
	if(l1 == null) return l2;
	if(l2 == null) return l1;
	
	ListNode cur_1 = l1;
	ListNode cur_2 = l2;
	
	ListNode head = new ListNode(0);   //返回head.next,避免了在循环中加额外判断
	ListNode cur  = head;              //用作指针
	
	int carry = 0;                     //进位
	
	while(cur_1!=null && cur_2!=null){
		int sum = cur_1.val + cur_2.val + carry;
		int digit = sum % 10;
		carry = sum / 10;
		
		ListNode newNode = new ListNode(digit);
		cur.next = newNode;
		
		cur = cur.next;
		cur_1 = cur_1.next;
		cur_2 = cur_2.next;
	}
	
	while(cur_1 != null){              //当list 1还有剩余节点
		int sum = cur_1.val + carry;
		int digit = sum % 10;
		carry = sum / 10;
		ListNode newNode = new ListNode(digit);
		cur.next = newNode;
		cur = cur.next;
		cur_1 = cur_1.next;
	}
	while(cur_2 != null){             //当list 2还有剩余节点
		int sum = cur_2.val + carry;
		int digit = sum % 10;
		carry = sum / 10;
		ListNode newNode = new ListNode(digit);
		cur.next = newNode;
		cur = cur.next;
		cur_2 = cur_2.next;
	}
	
	if(carry > 0){                   //容易忽略的错误:最高位仍有进位时,要额外新增一位
		ListNode newNode = new ListNode(carry);
		cur.next = newNode;
	}
	
	return head.next;        
    }
}



posted @ 2015-06-10 18:39  Mr.do  阅读(101)  评论(0编辑  收藏  举报