【leetcode】2.Add Two Numbers(c语言)

Description:

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Example:

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.

[ 题目链接 ]

注意边界:
1.不能将两个加数从链表里面取出来,加完将和再用链表表示,因为这些数可 能会大于int、float、double型的范围;
2.返回的链表,尾巴是否正确指向NULL?
3.推荐测试用例:
0+0=0
5+5=10
9999999991+9=10000000000

struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
   int num,carry=0,bit;
	struct ListNode* p1=l1, *p2=l2;
	struct ListNode* l3 = (struct ListNode*)malloc(sizeof(struct ListNode));
	num = (p1->val) + (p2->val);
	if (num / 10 != 0)	carry = 1;
	bit = num % 10;
	l3->val = bit;
	l3->next = NULL;
	struct ListNode* p3 = l3;
	p1 = p1->next;
	p2 = p2->next;

	//add
	while (p1&&p2)
	{
		num = (p1->val) + (p2->val)+carry;
		carry = 0;
		if (num / 10 != 0)	carry = 1;
		bit = num % 10;

		struct ListNode* new_node = (struct ListNode*)malloc(sizeof(struct ListNode));
		new_node->val = bit;
		new_node->next = NULL;
		p3->next = new_node;
		p3 = p3->next;
		p1 = p1->next;
		p2 = p2->next;
	}

	if (p1)
	{
		while (carry != 0&&p1!=NULL)
		{
			num = (p1->val) + carry;
			carry = num / 10;
			bit = num % 10;
			struct ListNode* new_node = (struct ListNode*)malloc(sizeof(struct ListNode));
			new_node->val = bit;
			new_node->next = NULL;
			p3->next = new_node;
			p3 = p3->next;
			p1 = p1->next;
		}
		if (carry == 0 && p1 == NULL)
		{
			p3->next = NULL;
			return l3;
		}
		else if (carry == 0)
		{
			p3->next = p1;
			return l3;
		}
		else if (p1 == NULL)
		{
			struct ListNode* new_node = (struct ListNode*)malloc(sizeof(struct ListNode));
			new_node->val = 1;
			new_node->next = NULL;
			p3->next = new_node;
			return l3;
		}
	}

	else if (p2)
	{
		while (carry != 0 && p2 != NULL)
		{
			num = (p2->val) + carry;
			carry = num / 10;
			bit = num % 10;
			struct ListNode* new_node = (struct ListNode*)malloc(sizeof(struct ListNode));
			new_node->val = bit;
			new_node->next = NULL;
			p3->next = new_node;
			p3 = p3->next;
			p2 = p2->next;
		}
		if (carry == 0 && p2 == NULL)
		{
			p3->next = NULL;
			return l3;
		}
		else if (carry == 0)
		{
			p3->next = p2;
			return l3;
		}
		else if (p2 == NULL)
		{
			struct ListNode* new_node = (struct ListNode*)malloc(sizeof(struct ListNode));
			new_node->val = 1;
			new_node->next = NULL;
			p3->next = new_node;
			return l3;
		}
	}

	else if (carry == 1)
	{
		struct ListNode* new_node = (struct ListNode*)malloc(sizeof(struct ListNode));
		new_node->val = 1;
		new_node->next = NULL;
		p3->next = new_node;
	}
	return l3;
}  

运行结果:
在这里插入图片描述
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/AXIMI/article/details/82783287