首页 > 其他 > 详细

LeetCode|Add Two Numbers

时间:2014-04-13 09:52:02      阅读:391      评论:0      收藏:0      [点我收藏+]

题目

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


思路

这道题是要通过链表来做的..节点的定义已经有了..

我是首先定义个头指针,但是这个指针和最终的结果没有关系的..

通过3个while来做(其实最多就2个会执行),遍历整个链表。并且用一个变量保存是否进位.整个算法就结束了..

代码

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
		ListNode result = new ListNode(0);
		ListNode head = result;
		int lastFlow = 0;
		if(l1 == null && l2 == null )
			return result;
		
		while(l1!=null && l2 !=null)
		{
			int num1 = l1.val;
			int num2 = l2.val;
			
		    int temp = l1.val + l2.val + lastFlow;
		    
		    if ( temp >=10 )
		    {
		    	lastFlow = 1;
		    	temp -= 10;
		    }
		    else
		    {
		    	lastFlow = 0;	
		    }
	    	ListNode node = new ListNode(temp);	    	
	    	result.next = node;
			result = result.next;
			l1 = l1.next;
			l2 = l2.next;
		}
		
		while(l1 != null)
		{
			int temp = l1.val + lastFlow;

		    if ( temp >=10 )
		    {
		    	lastFlow = 1;
		    	temp -= 10;		    	
		    }
		    else
		    {
		    	lastFlow = 0;
		    }
		    
		    ListNode node = new ListNode(temp);
	    	result.next = node;
	    	result = result.next;
			l1 = l1.next;
		}
		
		while(l2 != null)
		{
			int temp = l2.val + lastFlow;

		    if ( temp >=10 )
		    {
		    	lastFlow = 1;
		    	temp -= 10;		    	
		    }
		    else
		    {
		    	lastFlow = 0;
		    }
		    
		    ListNode node = new ListNode(temp);
	    	result.next = node;
	    	result = result.next;
			l2 = l2.next;
		}
		
		if( lastFlow !=0)
		{
			ListNode node = new ListNode(lastFlow);
			result.next = node;		
		}
//		ListNode l = head.next;
		return head.next;
    }
}


LeetCode|Add Two Numbers,布布扣,bubuko.com

LeetCode|Add Two Numbers

原文:http://blog.csdn.net/hwb1992/article/details/23526533

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!