1、题目
https://leetcode-cn.com/problems/add-two-numbers/
给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 单位 数字。
如果,我们将这两个数起来相加起来,则会返回出一个新的链表来表示它们的和。
您可以假设除了数字 0 之外,这两个数都不会以 0 开头。
示例:
2、实现
数据结构 :单链表 signly-linked list
分析:1、考虑到当一个列表为空时,value就是0了;
2、数学相加,有进位,进位只能是0或1;
3、要考虑到两个列表长度相同时,最后两位相加有进位的情况
复杂度:O(max(m,n))
Java
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode l3=new ListNode(0);
ListNode p=l3;
int temp=0;
int value=0;
int v1,v2,sum=0;
while(l1!=null||l2!=null){
v1=v2=0
if(l1!=null){
v1=l1.val;
l1=l1.next;
}
if(l2!=null){
v2=l2.val;
l2=l2.next;
}
sum=v1+v2+temp;
temp=sum/10;
p.next=new ListNode(sum%10);
p=p.next;
}
if(temp==1){
p.next=new ListNode(1);
}
return l3.next;
}
}
Python
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
if l1 is None:
return l2
if l2 is None:
return l1
l3=ListNode(0)
p=l3
temp=0 #表示进位
lsum=0
#l1和l2都不为空时
while l1 or l2:
a=b=0
if l1:
a=l1.val
l1=l1.next
if l2:
b=l2.val
l2=l2.next
lsum=a+b+temp
temp=lsum//10
p.next=ListNode(lsum%10)
p=p.next
#判断最后进位是否为1
if temp==1:
p.next=ListNode(1)
return l3.next
3、本题中语言点对比
点 | c++ | Java | Python | |
定义单链表 | typedef struct SListNode { DataType data; struct SListNode* next; }SListNode; | java.util里面有LinkedList类 public class ListNode { | class ListNode: def __init__(self, x): self.val = x self.next = None | |
新建一个node节点,并给data赋值 | SListNode<DataType> *s = new SListNode<DataType> s->data = 123; | ListNode l3=new ListNode(0); | l3=ListNode(0) | python new 都不需要 |
next | s=s->next | p=p.next | p=p.next | |
取值 | value=s->data | value=p.val | value=p.val | |
判断节点是否为空 | while (first != NULL) if (p == NULL) NULL都是大写 | while(l1!=null||l2!=null) if(l1!=null) if(l1==null)
null为小写 | if l1 is None while l1 or l2:
None 首字母大写 None,False,空字符串,空列表,空字典,空元组都相当于False 存在就是True
| |
数学除法符号 | a/b | a/b | a/b 除 a//b 取整除 | |
逻辑运算 | && || ! | && || ! | and or not |
4、python代码`if not x:` 和`if x is not None:`和`if not x is None:`使用
原文:https://blog.youkuaiyun.com/weixin_42153985/article/details/80235448
代码中经常有三中方式判断变量是否为None,主要有三种写法:
(1) if x is None:
(2)if not x:
(3)if not x is None:
在python中None,False,空字符串,空列表,空字典,空元组都相当于False,
eg:not None
not False
not''
not()
not{}
not[]
这些都会返回True
另外,在使用列表的时候,如果你想区分开x==[]和x==None两种情况,此时使用if not x:会出现问题
eg:x=[]
y=None
x is None //False
y is None//True
not x//True
not y//False
not x is None//这里应该理解成not( x is None)所以其会返回结果True
not y is None//not (y is None) 其会返回结果False
综上:if x is not None:这种写法最清晰,且不会出错,推荐这种写法。