LeetCode Add Two Numbers

Add Two Numbers 
You are given two linked lists representing two non-negative numbers. 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.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)

Output: 7 -> 0 -> 8

主要是單鏈表的操作.

代碼:

/*
 *兩個判斷精簡代碼以後在兩個數組或者兩個鏈表可以使用
 */
ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) 
{
	if(l1 == NULL) return l2;//如果有一條鏈是空的直接返回另一條鏈
	if(l2 == NULL) return l1;
	ListNode *l3;
	ListNode *list;
	int carryBit = 0, flag = 1;
	while(l1 || l2)
	{
		int temp  = carryBit;
		if(l1)//兩個判斷可以精簡代碼
		{
			temp += l1->val;
			l1 = l1->next;
		}
		if(l2)
		{
			temp += l2->val;
			l2 = l2->next;
		}
		carryBit = temp / 10;
		ListNode *q = new ListNode(temp % 10);//需要動態分配內存否則會出錯.
		if(flag)//如果是第一個結點
		{
			l3 = list = q;//l3用來指向頭結點, list用來循環操作.
			flag = 0;
		}
		else
		{
			list->next = q;
			list = list->next;
		}
	}
	if(carryBit)//兩條鏈都空了,但還是有進位.
	{
		ListNode *q = new ListNode(carryBit);
		list->next = q;
		carryBit = 0;
	}
	return l3;
}


發佈了62 篇原創文章 · 獲贊 1 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章