1. 程式人生 > >[LeetCode刷題菜鳥集] 2. Add Two Numbers 單鏈表表示的兩個數相加

[LeetCode刷題菜鳥集] 2. Add Two Numbers 單鏈表表示的兩個數相加

給定兩個非空連結串列來表示兩個非負整數。位數按照逆序方式儲存,它們的每個節點只儲存單個數字。將兩數相加返回一個新的連結串列。
你可以假設除了數字 0 之外,這兩個數字都不會以零開頭。

示例:

輸入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
輸出:7 -> 0 -> 8
原因:342 + 465 = 807
 

//main函式呼叫
int[] input1=new int[]{2,4,3};
int[] input2=new int[]{5,6,4};
ListNode l1=buildListNode(input1);
ListNode l2=buildListNode(input2);
addTwoNumbers(l1,l2);

//兩個數字相加 
public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    	//定義滿十進一的數
		int num = 0;
		//定義一個ListNode,作為連結串列頭
		ListNode proNode = new ListNode(0);
		//定義一個ListNode,接受兩數的和
		ListNode currentNode = new ListNode(0);
		//先連線兩個Node
		proNode.next=currentNode;
		
		do {
			//兩數相加
			int sum = (l1!=null?l1.val:0) + (l2!=null?l2.val:0) + num;
			//是否滿十
			num = sum/10;
			//得出個位數
			int result = sum%10;
			//填入結果
			currentNode.val = result;
			System.out.println("=="+currentNode.val);
			l1 = l1!=null?l1.next:l1;
			l2 = l2!=null?l2.next:l2;
			if(l1!=null || l2!=null || num!=0) {
				currentNode.next = new ListNode(0);
				currentNode = currentNode.next;
			}
		}while(l1!=null || l2!=null || num!=0);
		return proNode.next;
    }

public static class ListNode{
        int val;
        ListNode next;
        
        public ListNode(int x){
            val=x;
        }
      
    }
    
    public static ListNode buildListNode(int[] input){
        ListNode first = null,last = null,newNode;
        int num;
        if(input.length>0){
            for(int i=0;i<input.length;i++){
                newNode=new ListNode(input[i]);
                newNode.next=null;
                if(first==null){
                    first=newNode;
                    last=newNode;
                }
                else{
                    last.next=newNode;
                    last=newNode;
                }

            }
        }
        return first;
    }