LeetCode 2 : Add Two Numbers ---- 单链表相加
2016-05-16 17:34
399 查看
原题链接: https://leetcode.com/problems/add-two-numbers/
一:原题内容
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
二:AC代码
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
ret=ListNode(0)
ans=ret
flag=0
while True:
if l1:
flag+=l1.val
l1=l1.next
if l2:
flag+=l2.val
l2=l2.next
ret.val=flag%10
flag/=10
if l1 or l2 or flag:
ret.next=ListNode(0)
ret=ret.next
else:
break;
return ans
返回LeetCode 题解目录
一:原题内容
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
二:AC代码
/** * 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* pAns,* p; int flag=0; //标记余数 bool firstNode=true; //是否是第一个数,因为需要一个指针指向第一个节点,进而返回整个链表 int a=0; int b=0; while(l1||l2||flag) //注意这里的flag,如果输入 5 5 的话,余数1还得进行一次循环 { a=b=0; if(l1) { a=l1->val; l1=l1->next; } if(l2) { b=l2->val; l2=l2->next; } int sum=a+b+flag; if(sum>=10) { sum-=10; flag=1; } else flag=0; if(firstNode) { p=new ListNode(sum); pAns=p; firstNode=false; } /**********/ else { p->next=new ListNode(sum); p=p->next; } /**********/ /*对指针的理解又进一步了,下面是上一段代码的错误示例,提醒下自己 else { p=new ListNode(num); } p=p->next; */ } return pAns; } };
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
ret=ListNode(0)
ans=ret
flag=0
while True:
if l1:
flag+=l1.val
l1=l1.next
if l2:
flag+=l2.val
l2=l2.next
ret.val=flag%10
flag/=10
if l1 or l2 or flag:
ret.next=ListNode(0)
ret=ret.next
else:
break;
return ans
返回LeetCode 题解目录
相关文章推荐
- 【MyBatis框架点滴】——mybatis插入不显示,但是主键自增了?
- Linux,windows下nfs服务器的挂载
- PAT 1024
- C/C++中nth_element函数
- 环境变量3
- Specified key was too long;max key length is 767 bytes
- TensorFlow学习总结
- Redis中的数据结构-String与List
- android堆栈信息,android死锁致重启问题分析
- 根据根节点得到所有的叶子节点 CONNECT BY
- 解决sublime无法安装软件的问题
- Oracle表变化趋势追踪记录
- Java多线程——如何中断线程
- 动态路由协议之RIP
- CocoaPods error:The dependency '' is not used in any concrete target
- C++中的const函数与const_cast的矛盾
- oracle数据库创建表代码示例
- 环境变量2
- 小白排序之快速排序
- 2012年亚洲区域赛东京站