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

链表相加(二)

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<int>s1,s2;
        while(head1){
            s1.push(head1->val);
            head1 = head1->next;
        }
        while(head2){
            s2.push(head2->val);
            head2 = head2->next;
        }
        
        int carry = 0;
        ListNode* ans = nullptr;
        while(!s1.empty() or !s2.empty() or carry!=0){
            int a = s1.empty() ? 0 : s1.top();
            int b = s2.empty() ? 0 : s2.top();
            
            if(!s1.empty())
                s1.pop();
            if(!s2.empty())
                s2.pop();
            
            int cur = a + b + carry;
            carry = cur/10;
            cur = cur%10;
            auto p = new ListNode(cur);
            p->next = ans;
            ans = p;
        }
        return ans;
    }
};
全部评论

相关推荐

07-23 11:23
门头沟学院 Java
点赞 评论 收藏
分享
06-23 11:43
门头沟学院 Java
allin校招的烤冷...:我靠,今天中午我也是这个hr隔一个星期发消息给我。问的问题还是一模一样的😅
点赞 评论 收藏
分享
06-18 08:36
湖南大学 Java
运营你豪哥:没啥拷打的 1.增加量化结果,现在有点缺效果数据 2.突出复杂性,现在的项目描述有点像功能清单,强调一下技术难点和解决方案。
不给转正的实习,你还去吗
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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