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

链表相加(二)

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

/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 *	ListNode(int x) : val(x), next(nullptr) {}
 * };
 */

/*
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        ListNode* cur = head;
        ListNode* pre = nullptr;
        while(cur) {
            ListNode* next = cur->next;
            cur->next = pre;
            pre=cur;
            cur=next;
        }
        return pre;
    }
    ListNode* addInList(ListNode* head1, ListNode* head2) {
        // write code here
        ListNode* cur1 = reverseList(head1);//翻转链表
        ListNode* cur2 = reverseList(head2);//翻转链表
        ListNode* resHead=nullptr;
        int cnt = 0;
        int x1=0,x2=0,sum=0;
        while(cur1 || cur2) { //如果两个值的加和>10,就会产生进位,这个用来存储进位
            if(cur1==nullptr) x1=0; 
            else x1=cur1->val;
            if(cur2==nullptr) x2=0; 
            else x2=cur2->val;
            sum = x1+x2+cnt;
            cnt = sum / 10;
            ListNode* tmpNode = new ListNode(sum%10);
            tmpNode->next = resHead;
            resHead = tmpNode;
            if(cur1) cur1=cur1->next;
            if(cur2) cur2=cur2->next;
        }
        // 如果cnt>0 那么就说明存在进位还得插入一个节点
        if(cnt > 0) {
            ListNode* newNode = new ListNode(cnt);
            newNode->next = resHead;
            resHead = newNode;
        }
        return resHead;
    }
};*/

class Solution {
public:
    ListNode* addInList(ListNode* head1, ListNode* head2) {
        if(head1==nullptr) return head2;
        if(head2==nullptr) return head1;

        // 使用两个辅助栈,利用栈先进后出,相当于反转了链表
        stack<ListNode*> s1,s2;
        ListNode* p1 = head1;
        ListNode* p2 = head2;
        ListNode* resHead=nullptr;
        while(p1) {
            s1.push(p1);
            p1=p1->next;
        }
        while(p2) {
            s2.push(p2);
            p2=p2->next;
        }
        int sum = 0;
        int x1=0,x2=0,cnt=0;
        while(!s1.empty() || !s2.empty()) {
            if(!s1.empty()) x1 = s1.top()->val;
            else x1=0;
            if(!s2.empty()) x2 = s2.top()->val;
            else x2=0;
            sum = x1+x2+cnt;
            cnt = sum / 10;
            ListNode* tmpNode = new ListNode(sum % 10);
            tmpNode->next = resHead;
            resHead = tmpNode;
            if(!s1.empty()) s1.pop();
            if(!s2.empty()) s2.pop();
        }
        if(cnt>0) {
            ListNode* newNode = new ListNode(cnt);
            newNode->next = resHead;
            resHead=newNode;
        }
        return resHead;
    }
};

全部评论

相关推荐

10-22 12:03
山东大学 Java
程序员小白条:26届一般都得有实习,项目可以随便写的,如果不是开源社区的项目,随便包装,技术栈也是一样,所以本质应该找学历厂,多投投央国企和银行,技术要求稍微低一点的,或者国企控股那种,纯互联网一般都得要干活
应届生简历当中,HR最关...
点赞 评论 收藏
分享
11-03 13:18
门头沟学院 Java
包行:平时怎么刷算法题的哇,字节的手撕听说都很难
字节跳动工作体验
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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