【LeetCode】【445】【Add Two Numbers II】【链表】

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u012503241/article/details/82876479

题目: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.
解题思路:栈的一个很好的应用,当我们需要从后面往前算的时候,利用栈的先进后出的性质。注意题目要的结果,用头插法连接链表。逆序链表的话会导致超时。。而且题目中也不让这样做。
代码:

class ListNode {
      int val;
      ListNode next;
      ListNode(int x) { val = x; }
  }
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        //链表从后往前算,栈!
        Stack<Integer> s1 = new Stack<>();
        Stack<Integer> s2 = new Stack<>();
        while (l1!=null){
            s1.push(l1.val);
            l1 = l1.next;
        }
        while (l2!=null){
            s2.push(l2.val);
            l2=l2.next;
        }
        ListNode dummyNode = new ListNode(-1);
        int carry = 0;        //表示进位
        while (!s1.isEmpty() || !s2.isEmpty()){
            int sum = 0;
            if(!s1.isEmpty())sum = sum+s1.pop();
            if(!s2.isEmpty())sum = sum+s2.pop();
            sum = sum+carry;
            carry = sum/10;
            //头插法插入链表
            ListNode node = new ListNode(sum%10);
            node.next = dummyNode.next;
            dummyNode.next = node;
        }
//判断最后还有没有一位进位
        if(carry>0){
            ListNode node = new ListNode(1);
            node.next = dummyNode.next;
            dummyNode.next = node;
        }
        return dummyNode.next;
    }

猜你喜欢

转载自blog.csdn.net/u012503241/article/details/82876479