// leetcode2.cpp: 定义控制台应用程序的入口点。
//
#include "stdafx.h"
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
ListNode *newlist(int a[])
{
ListNode *head, *node, *cur;
head = node = new ListNode(0);
node->val = a[0];
for (int i = 1; a[i]!=NULL; i++)
{
cur = new ListNode(0);
cur->val = a[i];
cur->next = nullptr;
node->next = cur;
node = cur;
}
return head;
}
ListNode* test(ListNode* l1, ListNode* l2)
{
ListNode *head = NULL;
ListNode *p=NULL;
int carry = 0;
int sum;
while (l1 != NULL || l2 != NULL || carry != 0) {
sum = 0;
if (l1 != NULL) {
sum += l1->val;
l1 = l1->next;
}
if (l2 != NULL) {
sum += l2->val;
l2 = l2->next;
}
sum += carry;
carry = sum / 10;
sum %= 10;
ListNode *newNode = new ListNode(sum); //临时指针
if (head == NULL) {
head = newNode;
p = newNode;
}
else {
p->next = newNode;
p = p->next;
}
}
return head;
}
int main()
{
int a1[10] = { 6,6,3 };
int a2[10] = { 6,4,3 };
ListNode *l1 = new ListNode(0);
ListNode *l2 = new ListNode(0);
l1 = newlist(a1);
l2 = newlist(a2);
test(l1, l2);
}
leetcode第二题
最新推荐文章于 2022-08-12 20:27:28 发布