LeetCode OJ:Add Two Numbers (相加链表之数)
2015-10-11 17:47
387 查看
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
将两个链表上的数相加就可以,大于10进一位,注意下相加时候的细节就可以了,我这里
吧prev节点记录下来,这样最后多生成节点的时候便于将最后一个多余的节点删除:
感觉写的有点麻烦,应该有很多的重复代码可以改正,但是我暂时找不出来了,先这样吧。
更新下,以前脑子抽了写出了那样的代码。 其实三个while循环都可以放到一个while中, 下面用java在写一起,方法还是类似的:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
将两个链表上的数相加就可以,大于10进一位,注意下相加时候的细节就可以了,我这里
吧prev节点记录下来,这样最后多生成节点的时候便于将最后一个多余的节点删除:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { ListNode * curr = new ListNode(0); ListNode * root = curr; ListNode * prev = curr; int currVal = 0; while(l1 != NULL && l2 != NULL){ currVal = l1->val + l2->val; curr->val += currVal; curr->next = new ListNode(curr->val/10); curr->val%=10; prev = curr; curr = curr->next; l1 = l1->next; l2 = l2->next; } while(l1 != NULL){ curr->val += l1->val; curr->next = new ListNode(curr->val/10); curr->val %= 10; prev = curr; curr = curr->next; l1 = l1->next; } while(l2 != NULL){ curr->val += l2->val; curr->next = new ListNode(curr->val/10); curr->val %= 10; prev = curr; curr = curr->next; l2 = l2->next; } if(curr->val == 0){ prev->next = NULL; delete curr; } return root; } };
感觉写的有点麻烦,应该有很多的重复代码可以改正,但是我暂时找不出来了,先这样吧。
更新下,以前脑子抽了写出了那样的代码。 其实三个while循环都可以放到一个while中, 下面用java在写一起,方法还是类似的:
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { ListNode tmp = new ListNode(0); ListNode head = tmp; int carry = 0; while(l1!=null || l2!=null || carry != 0){ int val = ((l1 != null)?l1.val:0) + ((l2!=null)?l2.val:0) + carry; carry = carry/10 + val/10; val %= 10; tmp.next = new ListNode(val); tmp = tmp.next; l1 = l1!=null ? l1.next : l1; l2 = l2!=null ? l2.next : l2; } return head.next; } }
相关文章推荐
- ubuntu eclipse 解决android新建项目出现appcompat_v7报错和R文件无法生成的问题(windows同)
- a
- JVM 性能检测工具汇总
- 关联分析---Apriori
- Java读取Properties文件的六种方法
- C Runtime Library 的来历
- 1005. Programming Pattern (35)【待解决】
- 矩阵交换行
- 0011.scala中的apply
- 58 Length of Last Word
- HDU 2845 Beans (动态调节)
- ProgressBar
- ScrollView垂直滚动控件和HorizontalScrollView水平滚动控件
- hdoj Arithmetic Sequence 5400 (构造等差数列+技巧) 好题
- listView嵌套GridView引起的冲突
- PYTHON getattr setattr hasattr delattr内置函数
- ImageSwitcher图片切换控件
- Android音频系统之AudioPolicyService
- 获取[object Object]值
- 略看AMP-来自 Google 的移动页面优化方案