当前位置:网站首页>leetcode - 445. 两数相加 II

leetcode - 445. 两数相加 II

2022-07-05 08:14:00 zmm_mohua

leetcode - 445. 两数相加 II

题目

在这里插入图片描述

代码

#include <iostream>
#include <vector>
using namespace std;

typedef struct ListNode{
    
	int val;
	struct ListNode *next;
}ListNode, *LinkList;

void create(LinkList &head){
    
	int n;
	cin>>n;
	head = new ListNode;
	head->next = NULL;
	ListNode *tail = head;
	for(int i = 0; i < n; i++){
    
		ListNode *p = new ListNode;
		cin>>p->val;
		p->next = NULL;
		tail->next = p;
		tail = p;
	}
}

// 借助数组 
ListNode* addTwoNumbers1(ListNode* l1, ListNode* l2) {
    
	vector<int> nums1, nums2, res;
	while(l1){
    
		nums1.push_back(l1->val);
		l1 = l1->next;
	}
	while(l2){
    
		nums2.push_back(l2->val);
		l2 = l2->next;
	}
	int i = nums1.size() - 1;
	int j = nums2.size() - 1;
	int flag = 0, sum = 0, num = 0;
	while(i >= 0 || j >= 0){
    
		if(i < 0){
    
			sum = flag + nums2[j--];
		}else if(j < 0){
    
			sum = flag + nums1[i--];
		}else{
    
			sum = nums1[i--] + nums2[j--] + flag;
		}
		flag = sum / 10;
		num = sum % 10;
		res.push_back(num);
	}
	if(flag){
    
		res.push_back(flag);
	}
	int n = res.size();
	ListNode *head = new ListNode;
	head->next = NULL;
	ListNode *tail = head;
	for(int k = n - 1; k >= 0; k--){
    
		ListNode *p = new ListNode;
		p->val = res[k];
		p->next = NULL;
		tail->next = p;
		tail = p;
	}
	return head->next;
}

// 链表反转 
ListNode* reverse(ListNode *head){
    
	ListNode *pre = new ListNode;
	pre = NULL;
	ListNode *cur = head;
	while(cur){
    
		ListNode *temp = cur->next;
		cur->next = pre;
		pre = cur;
		cur = temp;
	}
	return pre;
}

ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
    
	ListNode *h1 = reverse(l1);
	ListNode *h2 = reverse(l2);
	ListNode *head = new ListNode;
	head->next = NULL;
	ListNode *tail = head;
	int sum = 0, flag = 0, num = 0;
	while(h1 || h2){
    
		if(!h1){
    
			sum = flag + h2->val;
			h2 = h2->next;
		}else if(!h2){
    
			sum = flag + h1->val;
			h1 = h1->next;
		}else{
    
			sum = flag + h1->val + h2->val;
			h1 = h1->next;
			h2 = h2->next;
		}
		flag = sum / 10;
		num = sum % 10;
		ListNode *p = new ListNode;
		p->val = num;
		p->next = NULL;
		tail->next = p;
		tail = p;
	}
	if(flag){
    
		ListNode *p = new ListNode;
		p->val = flag;
		p->next = NULL;
		tail->next = p;
		tail = p;
	}
	head = head->next;
	return reverse(head);
}

int main(){
    
	ListNode *l1, *l2, *res;
	create(l1);
	create(l2);
	l1 = l1->next;
	l2 = l2->next; 
	res = addTwoNumbers(l1, l2);
	while(res){
    
		cout<<res->val<<" ";
		res = res->next;
	}
	return 0;
}
原网站

版权声明
本文为[zmm_mohua]所创,转载请带上原文链接,感谢
https://blog.csdn.net/qq_42250642/article/details/125596066