Add Two Numbers

题目(Add Two Numbers)-medium


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

C语言解答

/*Definition for singly-linked list.
 struct ListNode {
     int val;
     struct ListNode *next;
 };*/
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
    struct ListNode* result;
    result = (struct ListNode*)malloc(sizeof(struct ListNode));//malloc struct ListNode result
    result->next = NULL;
    struct ListNode* tmp = result;
    struct ListNode* p = l1;
    struct ListNode* q = l2;
    int x = 0;
    int y = 0;
    int sum = 0;
    int carry = 0;
    
    while(p != NULL || q != NULL){
        x = 0;
        y = 0;   
        sum = 0;
        if(p != NULL){
            x = p->val;
        }
        if(q != NULL){
            y = q->val;
        }
        sum = x+y+carry;
        carry = sum/10;
        tmp->next = (struct ListNode*)malloc(sizeof(struct ListNode));
        tmp->next->next = NULL;//初始化的时候一定要指向NULL
        tmp->next->val = sum%10;
        tmp = tmp->next;
        if(p != NULL){
            p = p->next;
        }
        if(q != NULL){
            q = q->next;
        }
	}
	if(carry > 0){
	    tmp->next = (struct ListNode*)malloc(sizeof(struct ListNode));
	    tmp->next->next = NULL;//初始化的时候一定要指向NULL
	    tmp->next->val = carry;
	}
	return result->next;
}

收获

1. 不容易处理的点:
(1)l1和l2的长度可能不一样;
(2)最后一次相加后如果大于9,则还要考虑进位;
(3)循环进行的条件,以及val初始值的判断。
2. 如何初始化一个结构体,对于链表初始化时,一定要把它的next指向NULL,因为此时还没有开辟其next的空间,这也是在做这个题目时,一直无法Accepted的原因。

你可能感兴趣的:(LeetCode)