Leetcode 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 number 0 itself.

Follow up:
What if you cannot modify the input lists? In other words, reversing the lists is not allowed.
Example:

Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 8 -> 0 -> 7


思路:

这题主要是用到了这一数据结构。分别建立两个栈分别命名为stack1stack2。存储两个链表中的数据。这样栈的第一个数据就是链表中数据的最后一位,第二位数据是倒数第二位数据...

之后需要进行数据的计算,同时还有建造链表的工作。这里需要新建一个链表结点命名为head结点。之后每创建一个结点就插入到head结点之后,就是不断的改变head之后的结点,直到结束。


代码:

public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        Stackstack1 = new Stack();
        Stackstack2 = new Stack();
        ListNode node = l1;
        while(node != null){
            stack1.add(node.val);
            node = node.next;
        }
        node = l2;
        while(node != null){
            stack2.add(node.val);
            node = node.next;
        }
        int k=0;
        ListNode head = new ListNode(0);
        while(!stack1.isEmpty()||!stack2.isEmpty()){
            int sum = 0;
            if(!stack1.isEmpty()){
                sum += stack1.pop();
            }
            if(!stack2.isEmpty()){
                sum += stack2.pop();
            }
            sum += k;
            ListNode newnode = new ListNode(sum%10);
            newnode.next = head.next;
            head.next = newnode;
            k = sum/10;
        }
        if(k!=0){
            ListNode newnode = new ListNode(k);
            newnode.next = head.next;
            head.next = newnode;
        }
        return head.next;
}

你可能感兴趣的:(Leetcode 445 - Add Two Numbers II)