leetcode 2. add two numbers

来源:互联网 发布:网络创世纪uo服务端 编辑:程序博客网 时间:2024/03/29 09:34


//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


public class Solution {
 
 static class ListNode { 
       int val;
       ListNode next;
       ListNode(int x) {
        val = x;
     }
 }
 
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  int i = 0;
  ListNode a = new ListNode(0);
  ListNode b = new ListNode(0);
  ListNode c = new ListNode(0);
        c = a;
        ListNode d = new ListNode(0);
        d = b;
//自己写的数据
        a.val = 5;
  b.val = 5;
  while(i<2){
   
   a.next = new ListNode(0);
   b.next = new ListNode(0);
   a = a.next;
   b = b.next;
   a.val = 5;
   b.val = 5;
   
   i++;
  }
//例子数据
//        a.val = 2;
//        a.next = new ListNode(0);
//        a = a.next;
//        a.val = 4;
////        a.next = new ListNode(0);
////        a = a.next;
////        a.val = 3;
//        b.val = 5;
//        b.next = new ListNode(0);
//        b = b.next;
//        b.val = 6;
//        b.next = new ListNode(0);
//        b = b.next;
//        b.val = 4;
  ListNode e = addTwoNumbers(c,d);
  while(e!=null){
   System.out.println(e.val);
   e = e.next;
  }
 }
 
  public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
         ListNode res = new ListNode(0);
         ListNode p = new ListNode(0);
         p = res;
         boolean flag = true;
       
         while(l1!=null||l2!=null){
          int val1 = 0;
          int val2 = 0;
          int val = 0;
          if(l1!=null){
           
           val1 = l1.val;
           l1 = l1.next;
          }
          if(l2!=null){
           
           val2 = l2.val;
           l2 = l2.next;
          }
          if(flag == false){
           val = val1+val2+1;
           flag = true;
          }else{
           val = val1+val2;
          }
          if(val>=10) {
           flag = false;
           val = val%10;
          }
          
          res.next = new ListNode(val);
          res = res.next;
         }
         if(flag == false){
          res.next = new ListNode(1);
          res = res.next;
         }
        
         return p.next;
  }
}


0 0
原创粉丝点击