leetcode(2) - Add Two Numbers
来源:互联网 发布:淘宝上的自行车怎么样 编辑:程序博客网 时间:2024/04/20 19:34
题目要求:
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
/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) { if (!l1 && !l2) return NULL; if (!l1) return l2; if (!l2) return l1; struct ListNode *p1 = l1; struct ListNode *p2 = l2; int add_num = 0; //需要注意进位 (1)最后一位的进位需要新建结点存储进位 (2)如果两个链表的长度不一样的进位 int add_num_tmp = 0; struct ListNode *head = NULL; //需要注意尾插法第一次需要判断头结点为空的情况单独处理 struct ListNode *head_p = NULL; while(p1 && p2) { struct ListNode *new_Node = (struct ListNode *)malloc(sizeof(struct ListNode)); new_Node->next = NULL; add_num_tmp = add_num; add_num = (p1->val + p2->val + add_num_tmp) / 10; new_Node->val = (p1->val + p2->val + add_num_tmp) % 10; if (head == NULL) { head = new_Node; head_p = head; } else { head_p->next = new_Node; head_p = head_p->next; } p2=p2->next; p1=p1->next; } while (p1) { add_num_tmp = add_num; add_num = (p1->val + add_num_tmp) / 10; p1->val = (p1->val + add_num_tmp) % 10; head_p->next=p1; head_p = head_p->next; p1=p1->next; } while (p2) { add_num_tmp = add_num; add_num = (p2->val + add_num_tmp) / 10; p2->val = (p2->val + add_num_tmp) % 10; head_p->next=p2; head_p = head_p->next; p2=p2->next; } /* when add_num > 0 , we should create a new node to store */ if (add_num>0) { struct ListNode *new_Node = (struct ListNode *)malloc(sizeof(struct ListNode)); new_Node->val = add_num; new_Node->next = NULL; head_p->next = new_Node; head_p = head_p->next; } return head; }
0 0
- LeetCode 2 - Add Two Numbers
- LeetCode 2: Add Two Numbers
- Leetcode: Add Two Numbers (2)
- [leetcode 2] Add Two Numbers
- [Leetcode] 2 - Add Two Numbers
- LeetCode 2:《Add Two Numbers》
- LeetCode | #2 Add Two Numbers
- LeetCode 2 Add Two Numbers
- [Leetcode]2Add Two Numbers
- leetcode #2 Add Two Numbers
- leetcode-2 Add Two Numbers
- LeetCode 2 Add Two Numbers
- [leetcode] #2 Add Two Numbers
- LeetCode-2 Add Two Numbers
- LeetCode-2-Add Two Numbers
- Leetcode[2] Add Two Numbers
- LeetCode 2 Add Two Numbers
- LeetCode 2 Add Two Numbers
- 绿色instance client连接Oracle服务器的配置方法
- Nginx的location匹配问题
- Android View绘制原理的初步理解
- android studio 如何将工程提交到github
- 深入理解Java虚拟机
- leetcode(2) - Add Two Numbers
- 谢娜终于透露了至今未生孩子的原因,网友直呼接受不了
- 国庆过后老革命
- Java中对象锁和类锁举例
- 浅谈《家》中觉新形象与封建宗法制
- 第二章 示例一 二
- 欢迎使用CSDN-markdown编辑器
- 趋势2017校招 笔试题
- 内置函数