題目:
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.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)Output: 7 -> 0 -> 8
Subscribe to see which companies asked this question.
英語不好,題目都沒有讀懂,剛開始以為給的數字是按照從左到右是從高位到低位的順序,后來才知道,現在在這里翻譯一邊題目。給你兩個非空單鏈結構的列表,列表的每個元素包含一個非負整數,數的高低位已經倒置(從低位到高位)排列,每個節點只包含一位,將這兩個列表相加,返回結果列表。
假設兩個列表所給的最高位不會時0,除了列表是自然數0外。
這里可以提取模型,遍歷兩個list的模型,之前自己的思路一直都是,三個循環:第一個循環直到至少其中一個list為空,第二個循環到第一個list為空,第三個循環到第二個list為空(第二個第三個循環不一定會進入)。所以按照自己的思路,寫了一下代碼(C語言):
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) { struct ListNode *h1, *h2, *p, *head; int flag = 0; h1 = l1; h2 = l2; head = NULL; while (h1 != NULL && h2 != NULL) { if (head) { p->next = (struct ListNode*)malloc(sizeof(struct ListNode)); p = p->next; p->val = (h1->val + h2->val + flag) % 10; flag = (h1->val + h2->val + flag) / 10; p->next = NULL; h1 = h1->next; h2 = h2->next; } else { head = (struct ListNode*)malloc(sizeof(struct ListNode)); head->val = (h1->val + h2->val + flag) % 10; head->next = NULL; flag = (h1->val + h2->val + flag) / 10; p = head; h1 = h1->next; h2 = h2->next; } } while (h1 != NULL) { p->next = (struct ListNode*)malloc(sizeof(struct ListNode)); p = p->next; p->val = (h1->val + flag) % 10; p->next = NULL; flag = (h1->val + flag) / 10; h1 = h1->next; } while (h2 != NULL) { p->next = (struct ListNode*)malloc(sizeof(struct ListNode)); p = p->next; p->val = flag ? (h2->val + 1) % 10 : h2->val; p->next = NULL; flag = (h2->val + flag) / 10; h2 = h2->next; } if (flag) { p->next = (struct ListNode*)malloc(sizeof(struct ListNode)); p = p->next; p->val = 1; p->next = NULL; } return head;}(自己的代碼總是要debug好長時間,小毛病不斷,如果不是提交我自己都不知道哪里錯了,自己也很愁)
這里總結一下調試出來的bug:
1. 節點的next沒有注意造成的死循環,對策,以后凡是鏈的,先不求值,先寫next
2.flag一度認為和進位沒有關系,我智障了,小學的知識。
3.忘加最后的進位1(99+1)
看過大神的代碼,覺得好簡介,也學到一種遍歷兩個list的模型方法,一個循環,直到兩個都為空,循環內部先判斷是否為空,再進行相應的操作,代碼:
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) { struct ListNode *h, *p, *c1, *c2; int num = 0; c1 = l1; c2 = l2; h = p = NULL; while (c1 || c2) { num = num / 10; if (c1) { num += c1->val; c1 = c1->next; } if (c2) { num += c2->val; c2 = c2->next; } if (h == NULL) { h = (struct ListNode*)malloc(sizeof(struct ListNode)); h->next = NULL; h->val = num % 10; p = h; } else { p->next = (struct ListNode*)malloc(sizeof(struct ListNode)); p = p->next; p->val = num % 10; p->next = NULL; } } if (num/10) { p->next = (struct ListNode*)malloc(sizeof(struct ListNode)); p = p->next; p->val = 1; p->next = NULL; } return h;}
新聞熱點
疑難解答