《leetCode》:add two num
来源:互联网 发布:如何投诉网络运营商 编辑:程序博客网 时间:2024/06/05 04:09
《leetCode》:add two num
题目描述如下
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; * }; */ int list_len(struct ListNode* list){ if(list==NULL){ return 0; } int len=1; while(list->next!=NULL){ len++; list=list->next; } return len; }struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) { if(l1==NULL){//有效性检查 return l2; } if(l2==NULL){ return l1; } //求出两个链表的长度 int len1=list_len(l1); int len2=list_len(l2); //长链表代表大的数,短链表代表小的数 struct ListNode* highNum=l1; struct ListNode* lowNum=l2; int highLen=len1; int lowLen=len2; if(len1<len2){ highNum=l2; lowNum=l1; highLen=len2; lowLen=len1; } int ci=0;//表示进位 struct ListNode* cur1=highNum; struct ListNode* cur2=lowNum; struct ListNode* pre=NULL; while(lowLen>0){ int temp=cur1->val+cur2->val+ci; cur1->val=temp%10; ci=temp/10; pre=cur1; cur1=cur1->next; cur2=cur2->next; lowLen--; highLen--; } //将最后一个进位与长链表中剩余的结点相加 if(highLen>0&&ci>0){ while(highLen>0){ int temp=cur1->val+ci; cur1->val=temp%10; ci=temp/10; pre=cur1; cur1=cur1->next; highLen--; } if(ci>0){//需要创建新的结点 struct ListNode *newNode=(struct ListNode *)malloc(sizeof(struct ListNode)); if(newNode==NULL) exit(EXIT_FAILURE); newNode->val=ci; newNode->next=NULL; pre->next=newNode; } } else if(highLen==0&&ci>0){ struct ListNode *newNode=(struct ListNode *)malloc(sizeof(struct ListNode)); if(newNode==NULL) exit(EXIT_FAILURE); newNode->val=ci; newNode->next=NULL; pre->next=newNode; } return highNum;}
在线编程,感觉挺奇怪的:
在平时的代码中:我们都是这样再写是OK的:
ListNode* highNum;
但是,如果在线编译:这是不能够通过的,需要这样写才不提示编译错误。:
struct ListNode* highNum
贴上AC的结果
0 0
- 《leetCode》:add two num
- 《leetCode》:add two num
- leetcode4-Add Two Num
- add two num
- LeetCode #001 Two Num
- LeetCode 1 two num
- leetCode Q1:Two Num(java)
- leetcode 第一题 Two Num java
- LeetCode: Add Two Numbers
- LeetCode: Add Two Numbers
- [LeetCode]Add Two Numbers
- LeetCode Add Two Numbers
- Leetcode: Add Two Numbers
- [Leetcode] Add Two Number
- LeetCode : Add Two Numbers
- LeetCode Add Two Numbers
- [LeetCode] Add Two Numbers
- Leetcode : Add Two Numbers
- 硬盘分区2----GPT与MBR的区别
- Mysql 主键
- TabelView3D效果
- Ubuntu之旅——系统安装
- VS2013+CUDA7.5配置
- 《leetCode》:add two num
- C语言-关键字typedef的使用
- C语言-#define宏定义
- 逻辑覆盖
- 非主流代码
- 分享织梦DedeCMS设置全站Html网站地图教程
- HDU 1002 A + B Problem II 大数
- JAVA--单例设计模式
- UICollectionViewController简单操作(2)