您的位置:首页 > 其它

[LeetCode 2] Add Two Numbers Solution

2014-04-13 05:23 633 查看
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

Idea: The solution is straightforward. 

Check the NULL case 
Add the values together, if sum is larger than 10, then, we need a carry bit to record the value
/**
* Definition for singly-linked list.
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
if(l1 == NULL) return l2;
if(l2 == NULL) return l1;

int count = 0; // used for carry bit
ListNode *temp = new ListNode(-1); //declare a head node
ListNode *head = temp;
ListNode *h1 = l1;
ListNode *h2 = l2;

while(h1 != NULL || h2 != NULL){
int v1 = (h1 != NULL ? h1->val: 0); //it is a good ideas to get the value
int v2 = (h2 != NULL ? h2->val: 0);

int value = v1 + v2 + count;
ListNode *node = new ListNode(value % 10);
count = value / 10;

temp->next = node;
temp = temp->next;

h1 = (h1 != NULL ? h1->next : NULL); // it is h1 != NULL, but not h1->next !=NULL
h2 = (h2 != NULL ? h2->next : NULL);
}

if(count > 0){
temp->next = new ListNode(1);
}

ListNode *t = head; //delete the first head node
head = head->next;
delete t;

return head;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode LinkedList