lintcode-221. Add Two Numbers II

欢迎访问我的lintcode题解目录https://blog.csdn.net/richenyunqi/article/details/80686719


算法设计:

遍历两个给定链表,将两个链表中的元素分别放入两个栈中,然后两个栈同时弹出元素,进行加和,用头插法插入新链表中。

C++代码:

class Solution {
public:
    /**
     * @param l1: The first list.
     * @param l2: The second list.
     * @return: the sum list of l1 and l2.
     */
    ListNode * addLists2(ListNode * l1, ListNode * l2) {
        // write your code here
        stack<int>s1,s2;
        for(;l1!=nullptr;l1=l1->next)//遍历链表将链表元素放入栈中
            s1.push(l1->val);
        for(;l2!=nullptr;l2=l2->next)
            s2.push(l2->val);
        int carry=0;//进位
        ListNode*l3=nullptr;//新链表头指针
        while(!s1.empty()||!s2.empty()||carry!=0){
            int k1=0,k2=0;
            if(!s1.empty()){
                k1=s1.top();
                s1.pop();
            }
            if(!s2.empty()){
                k2=s2.top();
                s2.pop();
            }
            ListNode*p=new ListNode((k1+k2+carry)%10);//新建结点
            p->next=l3;
            l3=p;//更新头指针
            carry=(k1+k2+carry)/10;//更新进位
        }
        return l3;
    }
};

猜你喜欢

转载自blog.csdn.net/richenyunqi/article/details/80695255