leetcode第二题

// 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);
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值