2. Add Two Numbers
来源:互联网 发布:8090端口 编辑:程序博客网 时间:2024/06/16 08:48
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; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public: ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { ListNode* result = new ListNode(0); //通过new来申请动态内存,使用ListNode的构造函数初始化一个对象,表达式返回指向这个对象的指针 ListNode *r,*tmp; int count = 0; r = result; //最后返回result,故result指针是不动的,将其赋值给r while(l1&&l2) //非空 { int isum = count + l1->val + l2->val; count = isum/10; tmp = new ListNode(isum%10); r->next = tmp;//将r->next = tmp ,注意,结果链表的头节点不用来存值,而是从它的next开始存放,返回时返回result->next r = r->next; l1 = l1->next; l2 = l2->next; } if(l1 == NULL&&l2!=NULL) //l1空,l2非空 { r->next = l2; //将l2赋值给r->next if(count == 0) //如果上面的while循环结束时,count=0,即没有进位,则返回 { return result->next; //比如:l1: 2 3 / l2 1,3,5 } else //当有进位时,即count !=0,此时要考虑进位 { // 比如: 2 3 / 1 7 5 / 3 0 6 while(r->next&&count!=0) //此处用r->next 先判断r的next是否为空 { r = r->next; //不为空,则赋值给r int isum = r->val + count; r->val = isum%10; count = isum/10; } if(r->next == NULL && count!=0) //当r为空时,但是,此时上面的while返回的count!=0,则还想考虑 { // 例如: 1 / 9 9 /0 0 1 tmp = new ListNode(count); r->next = tmp; return result->next; } else return result->next; } } else if(l1 !=NULL&&l2==NULL) { r->next = l1; if(count == 0) { return result->next; } else { while(r->next&&count!=0) { r = r->next; int isum = r->val + count; r->val = isum%10; count = isum/10; } if(r->next == NULL && count!=0) { tmp = new ListNode(count); r->next = tmp; return result->next; } else return result->next; } } else { if(count == 0) return result->next; else { // count !=0,需要再次申请节点 2 3 4 / 1 3 6 / 3 6 0 1 tmp = new ListNode(count); r->next = tmp; return result->next; } } }};
总结:
此题为链表的操作:
1.因为定义类型指针如ListNode *tmp ,指针变量占4字节(32位机),再申请动态内存对象时,注意使用tmp = new ListNode() ,将tmp指针指向动态分配的对象,然后再进行后续操作,最后delete它
2.while中一般多用while(p->next)来判断,如果进入while循环,再将p = p->next;
3.此题中,返回result时,不是直接返回result,而是返回它的next;因为这样处理使编写程序的过程中简单点,需要借鉴
4.此题中,当l1或l2为空时,要考虑到count!=0情况;
0 0
- 2.Add Two Numbers
- 2.Add Two Numbers
- 2.Add Two Numbers
- 2.Add Two Numbers
- 2. Add Two Numbers
- 2. Add Two Numbers
- 2.Add Two Numbers
- 2. Add Two Numbers
- 2. Add Two Numbers
- 2. Add Two Numbers
- 2. Add Two Numbers
- 2. Add Two Numbers
- 2. Add Two Numbers
- 2. Add Two Numbers
- 2. Add Two Numbers
- 2.Add Two Numbers
- 2. Add Two Numbers
- 2. Add Two Numbers
- linux常用基本命令
- myeclipse自动化提示
- 关于掉帧问题
- Linux内核源代码顶层目录下的Makefile文件分析一
- 《Python编程》笔记(三)
- 2. Add Two Numbers
- 方格取数 (Standard IO)
- 浪迹万能数据库v1.2官方版
- Python多线程详解
- Android学习之SharedPreferences数据存储
- FileUtils
- springMVC与json结合
- Git使用
- 详解Pyqt4事件和信号