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

链表相加(二)

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

/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 *	ListNode(int x) : val(x), next(nullptr) {}
 * };
 */
#include <ios>
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param head1 ListNode类 
     * @param head2 ListNode类 
     * @return ListNode类
     */
    ListNode* addInList(ListNode* head1, ListNode* head2) {
        // write code here
        //分别遍历一遍两个列表
        vector<int> listA;
        vector<int> listB;
        while(head1 != nullptr){
            listA.push_back(head1->val);
            if(head1->next!= nullptr){
                head1 = head1->next;
            }
            else{
                break;
            }
        }
        while(head2 != nullptr){
            listB.push_back(head2->val);
            if(head2->next!= nullptr){
                head2 = head2->next;
            }
            else{
                break;
            }
        }
        // 将数值表从后往前进行计算求和,获得新的数值表
        //cout<<"长度分别为"<< listA.size()<<","<<listB.size()<<endl;
        int end1 = listA.size();
        int end2 = listB.size();
        int UpNum = 0;
        vector<int> listNum;
        while(end1 > 0 || end2 > 0){
            end1 = end1 - 1;
            end2 = end2 - 1;
            
            int x = end1>=0?listA[end1]:0;
            int y = end2>=0?listB[end2]:0;
            int tmpNum = x+y+UpNum;
            cout<<x<<","<<y<<","<<tmpNum<<endl;
            int res;
            if(tmpNum > 9){
                res = tmpNum%10;
                UpNum = (tmpNum)/10;
            }
            else{
                res = tmpNum;
                UpNum = 0;
            }
            listNum.push_back(res);
        }
        
        // 用node将数值放入
        ListNode* nodeB = new ListNode(-1);
        ListNode* nodeA = nodeB;
        if(UpNum!=0){
            listNum.push_back(UpNum);
        }
        for (int j = listNum.size()-1; j>=0; j--) {
            cout<< listNum[j];
            nodeB->next = new ListNode(listNum[j]);
            nodeB = nodeB->next;
        }
        
        return nodeA->next;
    }
};

全部评论

相关推荐

不愿透露姓名的神秘牛友
07-24 12:26
点赞 评论 收藏
分享
陆续:不可思议 竟然没那就话 那就我来吧 :你是我在牛客见到的最美的女孩
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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