ACM之兩數相加問題

題目以下:java

圖片.png

這道題我的以爲沒涉及到什麼算法,就是考數據結構——鏈表。那首先來簡單複習一下鏈表:算法


     鏈表(Linked list)是一種線性表,可是並不會按線性的順序存儲數據,而是在每個節點裏存到下一個節點的指針(Pointer)。因爲沒必要須按順序存儲,鏈表在插入的時候能夠達到O(1)的複雜度,比另外一種線性表順序錶快得多,可是查找一個節點或者訪問特定編號的節點則須要O(n)的時間,而順序表相應的時間複雜度分別是O(logn)和O(1)。數據結構

圖片.png

使用Java定義鏈表:
dom

public static class ListNode{
          int data;
          ListNode next;
          ListNode(int x){
              data = x;
          }
}

    

    在這道題中,因爲位數按照逆序存儲,即鏈表的頭結點就是個位,而後一次是十位、百位...,因此能夠直接從頭結點開始相加,只須要將進位保存下來加到下一位的和上便可。感受這道題沒什麼可說的,本身作的時候就是對鏈表的操做不熟練,因此重點仍是在數據結構上。ide

Java代碼實現this

package Leetcode;
import java.util.Random;
public class TwoPlusBter {
     
     // TODO create a listNode class
     public static class ListNode{
          int data;
          ListNode next;
          ListNode(int x){
              data = x;
          }
          // FOR i can output the ListNode with a String
          public String toString(){
              String res = "";
              for(ListNode p = this;p != null;p = p.next){
                   res += p.data + " ";
              }
              return res;
          }
          
          
     }
     
     public static ListNode Solution(ListNode l1,ListNode l2){
          ListNode res = new ListNode(0);
          ListNode cur = res;//cur做爲res的引用,改變cur即改變res
          
          for(int carry = 0;l1 != null || l2 != null || carry > 0;){
              int val1 = l1 != null ? l1.data:0;
              int val2 = l2 != null ? l2.data:0;
              
              l1 = l1 != null ? l1.next:null;
              l2 = l2 != null ? l2.next:null;
              
              int sum = val1 + val2 + carry;//各位相加
              carry = sum / 10; //carry做爲進位:0 or 1
              cur.next = new ListNode(sum % 10);
              cur = cur.next;
              //System.out.println("aaa");
              
          }
            res = res.next;
          //System.out.println("aaa");
          return res;
     }
     
     public static ListNode Random(){
          ListNode test = new ListNode(0);
          ListNode cur = test , del = null;
          Random rd = new Random();
          int n = rd.nextInt(9) + 1; //生成[0,9)的隨機數
          System.out.println("n="+n);
          for(int i = 0;i<n;i++){
              cur.data = rd.nextInt(10);
              cur.next = new ListNode(0);
              del = cur; // del指向cur的前一個結點
              cur = cur.next;
              //這樣的話跳出循環時cur會出現一個多餘的結點,因此利用del將此結點刪除
          }
          del.next = null;
          return test;
     }
     
     public static void main(String[] args){
          ListNode l1 = Random();
          System.out.println(l1.toString());
          ListNode l2 = Random();
          System.out.println(l2.toString());
          ListNode res = Solution(l1,l2);
          System.out.println(res.toString());
     }
}
相關文章
相關標籤/搜索