Add Two Numbers
来源:互联网 发布:mac怎么装office软件 编辑:程序博客网 时间:2024/06/16 05:32
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
这道题主要容易忽略的几点在:
1 , 链表 L1 和 L2 不一定是一样长的 ,设计的程序必须考虑到.
2, 这道题的问题主要不光要考虑到时间复杂度(感觉都能过),还要注意要空间复杂度(不要浪费空间).
其他应该不是问题,我的代码如下:
(老实说这个解法并不太好,只是为了完成任务,如果有更好的希望能告知我)
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) { int n,coun =0; struct ListNode *ptr ,*head ; head =ptr= malloc(sizeof(struct ListNode)); for( ; ;) { if( l1 !=NULL) { n = l1->val; l1 =l1->next; }else { n =0; } if( l2 != NULL) { n += l2->val; l2 = l2->next; } n += coun; ptr->next = malloc(sizeof(struct ListNode)); ptr = ptr->next; ptr->val = (n)%10; coun =n/10; if(l1==NULL &&l2==NULL&&coun==0) {ptr->next =NULL; break; } } ptr=head->next; free(head); return(ptr); }
0 0
- Add two numbers & Add binary
- LeetCode: Add Two Numbers
- Add Two Numbers
- LeetCode: Add Two Numbers
- [LeetCode]Add Two Numbers
- LeetCode Add Two Numbers
- Leetcode: Add Two Numbers
- Add Two Numbers
- LeetCode : Add Two Numbers
- LeetCode Add Two Numbers
- [LeetCode] Add Two Numbers
- LeetCode4: Add Two Numbers
- Leetcode : Add Two Numbers
- Add Two Numbers
- 【leetcode】Add Two Numbers
- add two numbers
- Add Two Numbers
- Add Two Numbers
- L23数组指针分析
- 关于android事件分发的总结
- Android网络编程之http发送/请求服务
- 分手后极品留言
- Rightmost Digit
- Add Two Numbers
- 再说MySQL中的 table_id
- speex编解码在android上实现
- 5.2-3
- L24c语言中的字符串
- jquery的$.extend和$.fn.extend作用及区别
- CF#304Div2
- 2015`06`03实习面试收获
- [Servlet]什么是Servlet