LeetCode刷题笔记(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

题意分析: 

给定两个用于表示两个非负整数的非空链表,其中数是按顺序的方式挨个存放在链表中(即...万千百十个)。请将这两个正整数求和,并把和以顺序的方式存放在一个新链表中。

解答如下:

方法一(组合法)

先将两链表分别进行反转,再根据(https://blog.csdn.net/Vensmallzeng/article/details/88619871)中的方法二,将两链表对应相加,最后将所得链表再进行一次反转,即为题目所求结果。

class Solution{
public:
    ListNode* addTwoNumbers( ListNode* l1, ListNode* l2){   
        ListNode* num1 = ReverseList( l1 );
        ListNode* num2 = ReverseList( l2 );
        ListNode* dummy = new ListNode(-1);
        ListNode* cur = dummy;
        int carry = 0;
        while ( num1 || num2 )
           {int val1 = num1 ? num1 -> val : 0;
            int val2 = num2 ? num2 -> val : 0;
            int sum = val1 + val2 + carry;
            carry = sum / 10;
            cur -> next = new ListNode( sum % 10 );
            cur = cur -> next;
            if( num1 ) num1 = num1 -> next;
            if( num2 ) num2 = num2 -> next;
           }
        if (carry) cur -> next = new ListNode( carry );
        return ReverseList( dummy -> next );
    }
    ListNode* ReverseList(ListNode* head){    //反转链表,由于反转后头节点在尾部,所以不需要新建dummy
        ListNode* pre = NULL;
        ListNode* cur = head;
        while( cur ){
             ListNode* nex = cur -> next;
             cur -> next = pre;
             pre = cur;
             cur = nex;
        }
        return pre;
    }
};

提交后的结果如下: 

方法二(堆栈法) 

先创建两个栈,用于保存两个链表中的节点值,然后利用栈的后进先出的特点就可以从后往前取节点值,如果栈不为空,则将栈顶节点值加入sum中,然后将cur节点值赋为sum%10,并新建一个进位节点head,赋值为sum/10,如果没有进位,那么就是0,紧接着head后面连上cur,再将cur指向head,直到循环退出后,若cur的值为0则返回cur->next,不为0则返回cur即可。

class Solution{
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2){
      stack<int> s1;
      stack<int> s2;
      while( l1 ) { s1.push( l1->val ); l1 = l1 -> next; }
      while( l2 ) { s2.push( l2->val ); l2 = l2 -> next; }

      int sum = 0;
      ListNode* cur = new ListNode(0);
      while( !s1.empty() || !s2.empty() ){
          if( !s1.empty() ){ sum += s1.top(); s1.pop();}
          if( !s2.empty() ){ sum += s2.top(); s2.pop();}
          cur -> val = sum % 10;
          ListNode* head = new ListNode( sum / 10 );   //新建节点值赋值为sum/10,是为了避免最高位相加产生进位时,在退出循环后返回值不出错
          head -> next = cur;
          cur = head;
          sum = sum / 10;
       }
        return cur -> val != 0 ?  cur : cur -> next;

    }
};

提交后的结果如下: 

日积月累,与君共进,增增小结,未完待续。 

猜你喜欢

转载自blog.csdn.net/Vensmallzeng/article/details/88633686