【LeetCode】算法题2 Add Two Numbers的归纳

来源:互联网 发布:linux如何清除dns缓存 编辑:程序博客网 时间:2024/06/06 18:58

原题链接

题目:

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


贴代码:

#include "addTwoNums.h"struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {struct ListNode* head = (struct ListNode*)malloc(sizeof(struct ListNode));struct ListNode* resultList = NULL;struct ListNode* pre = head;int carry = 0;// carry positionint sum;int standard;pre->next = NULL;while (l1 && l2) {resultList = (struct ListNode*)malloc(sizeof(struct ListNode));pre->next = resultList;pre = resultList;resultList->next = NULL;sum = l1->val + l2->val + carry;standard = sum - 10;if (standard < 0) {// no carryresultList->val = sum;carry = 0;}else {carry = 1;resultList->val = standard;}l1 = l1->next;l2 = l2->next;}while (l1) {resultList = (struct ListNode*)malloc(sizeof(struct ListNode));pre->next = resultList;pre = resultList;resultList->next = NULL;sum = l1->val + carry;standard = sum - 10;if (standard < 0) {carry = 0;resultList->val = sum;}else {carry = 1;resultList->val = standard;}l1 = l1->next;}while (l2) {resultList = (struct ListNode*)malloc(sizeof(struct ListNode));pre->next = resultList;pre = resultList;resultList->next = NULL;sum = l2->val + carry;standard = sum - 10;if (standard < 0) {carry = 0;resultList->val = sum;}else {carry = 1;resultList->val = standard;}l2 = l2->next;}if (carry == 1) {resultList = (struct ListNode*)malloc(sizeof(struct ListNode));pre->next = resultList;resultList->val = 1;resultList->next = NULL;}return head->next;}
在leetcode上时间排名