* LeetCode【2】. Add Two Numbers--java实现

* LeetCode【2】. Add Two Numbers--java实现_第1张图片
coding

第二道题 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

简单来说,给两个单向链表,元素反向相加并以同样规则进行储存。注意进位!

以下是我写的java程序:

一、常规做法:

逐一抽取计算,并考虑其中某个到达链尾的情况。

/**
* Definition for singly-linked list. 
* public class ListNode {
* int val;
 * ListNode next;
 * ListNode(in x) { val = x; } 
*  }
 */
public class Solution { 
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    ListNode slist = new ListNode(0); 
    ListNode clist = slist;
    ListNode nlist = new ListNode(0); 
    //int sval = 0;
    int flag = 0; // 进位 
    //1. if First Node of l1 or l2 is null       
    if(l1==null||l2==null){
       return (l1==null)?((l2==null)?(slist):(l2)):(l1);
    }

    //2.1 当l1,l2都非链尾时,loop 
    while(true)
    {
      clist.val = (l1.val + l2.val + flag)%(10);
      flag = (l1.val + l2.val + flag)/10; 
      //next node 
      l1 = l1.next;
      l2 = l2.next;
      //2.1.1 若任意一个为链尾,则跳出             
      if(l1==null||l2==null){
            break;
       }else{ 
        clist.next= new ListNode(0);
        clist =clist.next; } };//while 
       //2.2 如果两个同时为链尾时              
       if(l1==null&&l2==null) 
       {
           //2.2.1 若两个为链尾且有进位,结果需进位 
          if(flag==1){ 
             nlist = new ListNode(flag); 
             clist.next = nlist;
           }else{ 
            return slist; 
             }
      }else //2.2 一个到达链尾、一个还未 
      {
         ListNode onelist = new ListNode(0);
         if(l1==null) 
         {onelist = l2;
          }else
         {onelist = l1; }
          while(onelist!= null)
        { 
         clist.next = new ListNode(0);
         clist = clist.next; 
         clist.val = (onelist.val + flag)%10;
         flag = (onelist.val + flag)/10;
         onelist = onelist.next; 
     } //2.2.1 当另外一个也到达链尾,判断是否有进位      
      if(flag==1)
      {
          clist.next = new ListNode(flag);
       }
  } 
  return slist;
 }
}

二、思路清晰的做法:

将链表先读取为数值类型,相加后再将结果转为规定链表。该方法思路十分清晰简单,但是要逐一是否会溢出,时间及空间复杂度增加等问题。

三、更优方案:

此处有更好更简洁的解决方案供参考::Leetcode – Add Two Numbers (Java)。该方法分别判断两个链表是否到链尾了。就不需要像一那样考虑多种情况,似乎很多问题都可以有将各种情况统一的方式。下次做之前要多思考是否有这种方式。

你可能感兴趣的:(* LeetCode【2】. Add Two Numbers--java实现)