题解 | #链表相加(二)#

链表相加(二)

http://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */

// 利用栈来做,代码好长啊,和其他人题解不太一样,发出来看看^^ ^^ ^_^

class Solution {
public:
    /**
     * 
     * @param head1 ListNode类 
     * @param head2 ListNode类 
     * @return ListNode类
     */
    ListNode* addInList(ListNode* head1, ListNode* head2) {
        // write code here
        stack<ListNode*> arr1, arr2;

        if(!head1) return head1;
        if(!head2) return head2;
        
        ListNode *p1 = head1, *p2 = head2;
        while(p1)
        {
            arr1.push(p1);
            p1 = p1->next;
        }
        while(p2)
        {
            arr2.push(p2);
            p2 = p2->next;
        }
        
        int flag = 0;
        int sum = 0;
        ListNode *l = nullptr, *r = nullptr;
        while(arr1.size() && arr2.size())
        {
            p1 = arr1.top();
            arr1.pop();
            p2 = arr2.top();
            arr2.pop();
            
            sum = p1->val + p2->val + flag;
            flag = sum / 10;
            sum = sum % 10;
            

            l = new ListNode(sum);
            l->next = r;
            r = l;
        }
        
        while(arr1.size())
        {
            p1 = arr1.top();
            arr1.pop();
            
            sum = p1->val + flag;
            flag = sum / 10;
            sum = sum % 10;
            
            l = new ListNode(sum);
            l->next = r;
            r = l;
        }
        while(arr2.size())
        {
            p2 = arr2.top();
            arr2.pop();
            
            sum = p2->val + flag;
            flag = sum / 10;
            sum = sum % 10;
            
            l = new ListNode(sum);
            l->next = r;
            r = l;
        }
        if(flag != 0)
        {
            l = new ListNode(flag);
            l->next = r;
            r = l;
        }
        
        return l;
    }
};
全部评论

相关推荐

点赞 评论 收藏
分享
积极的小学生不要香菜:你才沟通多少,没500不要说难
点赞 评论 收藏
分享
头顶尖尖的程序员:我是26届的不太懂,25届不应该是找的正式工作吗?为什么还在找实习?大四还实习的话是为了能转正的的岗位吗
点赞 评论 收藏
分享
不亏是提前批,神仙打架,鼠鼠不配了
站队站对牛:现在92都报工艺岗了
投递韶音科技等公司8个岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务