2.5---链表来进行加法,链式A+B(CC150)

这里是用了自己的方法,和书本不一样。

import java.util.HashSet;
import java.util.Set;



class ListNode{
    int val;
    ListNode next;
    ListNode(int x){
        val = x;
    }
}

public class Solution{

    public static void main(String[] args){
        ListNode head = new ListNode(3);
        head.val = 3;
        ListNode node = new ListNode(1);
        node.val = 1;
        head.next = node;
        ListNode tmp = head;
        while(tmp != null){
            System.out.println(tmp.val);
            tmp = tmp.next;
        }
        
        System.out.println("delete");
        tmp = sum(null,null);
    
        while(tmp != null){

            System.out.println(tmp.val);
            tmp = tmp.next;
        }
        
        
    }

    public static ListNode sum (ListNode head1, ListNode head2){
        if(head1 == null ) return head2;
        if(head2 == null) return head1;
        
        int n1 = 0;
        int n2 = 0;
        int sum = 0;
        int flag = 0;
        while(head1 != null){
            n1 += head1.val * Math.pow(10, flag++);
            head1 = head1.next;
        }
        flag = 0;
        while(head2 != null){
            n2 += head2.val * Math.pow(10, flag++);
            head2 = head2.next;
        }
        
        sum = n1 + n2;
        System.out.println("sum = " + sum);
        int digit = sum % 10;
        ListNode head = new ListNode(digit);
        ListNode res = head;
        sum /= 10;
        while(sum != 0){
            digit = sum % 10;
            ListNode n = new ListNode(digit);
            head.next = n;
            head = head.next;
            sum /= 10;
        }
        return res;
    }
}

 

posted @ 2015-12-17 23:14  创业-李春跃-增长黑客  阅读(176)  评论(0编辑  收藏  举报