leetcode--Add Two Numbers

来源:互联网 发布:淘宝助理5.7 编辑:程序博客网 时间:2024/06/05 06:20

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

[java] view plain copy
  1. /** 
  2.  * Definition for singly-linked list. 
  3.  * public class ListNode { 
  4.  *     int val; 
  5.  *     ListNode next; 
  6.  *     ListNode(int x) { val = x; } 
  7.  * } 
  8.  */  
  9. public class Solution {  
  10.     public ListNode addTwoNumbers(ListNode l1, ListNode l2) {  
  11.         if(l1==nullreturn l2;  
  12.         if(l2==nullreturn l1;  
  13.         ListNode head = new ListNode(0);  
  14.         ListNode cur = head;  
  15.         int flag = 0;  
  16.         while(l1!=null&&l2!=null){  
  17.             int t = (l1.val+l2.val+flag);  
  18.             cur.next = new ListNode(t%10);  
  19.             flag = t/10;  
  20.             cur = cur.next;  
  21.             l1 = l1.next;  
  22.             l2 = l2.next;  
  23.         }  
  24.         while(l1!=null){  
  25.             int t = (l1.val+flag);  
  26.             cur.next = new ListNode(t%10);  
  27.             flag = t/10;  
  28.             cur = cur.next;  
  29.             l1 = l1.next;  
  30.         }  
  31.         while(l2!=null){  
  32.             int t = (l2.val+flag);  
  33.             cur.next = new ListNode(t%10);  
  34.             flag = t/10;  
  35.             cur = cur.next;  
  36.             l2 = l2.next;  
  37.         }         
  38.         if(flag>0){  
  39.             cur.next = new ListNode(flag);  
  40.         }  
  41.         return head.next;  
  42.     }  
  43. }  

原文链接http://blog.csdn.net/crazy__chen/article/details/45442077

原创粉丝点击