《leetCode》:add two num
2015-10-29 22:37
344 查看
《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的结果
相关文章推荐
- 对于OAuth的理解
- 二叉堆(优先队列)
- 最快的3x3中值模糊
- hdu 1596 find the safest road
- Android常用知识点
- 硬盘分区2----GPT与MBR的区别
- 同行评审的五个方法都是怎样实现的有什么区别
- Apache 2.2主配置文件/etc/httpd/conf/httpd.conf配置解说
- 对抽屉效果几大github第三方库的
- LeetCode:Word Pattern
- Oracle连接查询内容整理
- 计算机的基本组成
- java复习:Map接口、Collections接口
- 通讯录
- 利用Javascript去操作UIWebView的广告内容
- HDU 1003 联机算法
- Java中server层、modle层和dao层的区别和功能介绍
- 二叉堆(优先队列)
- 测试用例各要素编写规范
- 【FastDev4Android框架开发】AndroidAnnnotations注入框架使用之Injection标签详解(十)