两个链表相加的和445. Add Two Numbers II

题目:

You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    /*
    解题思路:将链表存入集合中,然后相加即可,定义一个变量flage记录进位
    */
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode result=new ListNode(0);//头结点
        LinkedList<Integer> list1=new LinkedList<Integer>();
        LinkedList<Integer> list2=new LinkedList<Integer>();
        while(l1!=null){
            list1.add(l1.val);
            l1=l1.next;
        }//while
        while(l2!=null){
            list2.add(l2.val);
            l2=l2.next;
        }//while
        int flage=0;
        //头插法建立链表,集合是先进后出的方式
        while(list1.size()!=0&&list2.size()!=0){
            int num=list1.removeLast()+list2.removeLast()+flage;
            flage=num/10;
            num=num%10;
            ListNode temp=new ListNode(num);
            temp.next=result.next;
            result.next=temp;
        }//while
        while(list1.size()!=0){
            int num=list1.removeLast()+flage;
            flage=num/10;
            num=num%10;
            ListNode temp=new ListNode(num);
            temp.next=result.next;
            result.next=temp;
        }
        while(list2.size()!=0){
            int num=list2.removeLast()+flage;
            flage=num/10;
            num=num%10;
            ListNode temp=new ListNode(num);
            temp.next=result.next;
            result.next=temp;
        }
        //考虑进位的时候,两个集合均为空的情况,例如{5}  {5}相加之后需要进位1
        if(flage!=0){
            ListNode temp=new ListNode(flage);
            temp.next=result.next;
            result.next=temp;
        }
        return result.next;
    }
}


猜你喜欢

转载自blog.csdn.net/zyilove34/article/details/78071987
今日推荐