add two numbers

看题一脸懵逼,看中文都很懵逼,链表怎么实现的,点了debug才看到一些代码

改一下,使本地可以跑起来

# 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
"""
print(listNodeToString(l1))
print(l1.val)
print(l1.next.val) def stringToListNode(input):
numbers=input
# Now convert that list into linked list
dummyRoot = ListNode(0)
ptr = dummyRoot
for number in numbers:
ptr.next = ListNode(number)
ptr = ptr.next ptr = dummyRoot.next
return ptr def listNodeToString(node):
if not node:
return "[]" result = ""
while node:
result += str(node.val) + ", "
node = node.next
return "[" + result[:-2] + "]" def main(): while True:
try: line = [2,4,3]
l1 = stringToListNode(line);
line = [5,6,4]
l2 = stringToListNode(line); ret = Solution().addTwoNumbers(l1, l2) out = listNodeToString(ret);
print(out) #throw
raise StopIteration
except StopIteration:
break if __name__ == '__main__':
main()
第1次提交
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None ############## start ############## def listNodeToInt(listN):
'''链表转整数'''
result=0
i=0
node=listN
while True: if not isinstance(node,ListNode):
break
result += node.val*10**i
node=node.next
i+=1 return result def intToListNode(num):
'''整数转链表,抄袭stringToListNode '''
dummyRoot = ListNode(0)
ptr = dummyRoot
while True:
if num == 0:
break
number=num%10
num=num//10 ptr.next = ListNode(number)
ptr = ptr.next ptr = dummyRoot.next
return ptr class Solution:
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
#list1=listNodeToString(l1)
#print(list1) i1=listNodeToInt(l1)
i2=listNodeToInt(l2)
i3=i1+i2
#print(i1,i2)
#print(i3)
l3=intToListNode(i3)
#print(listNodeToString(l3)) return l3 ############## end ############## def stringToListNode(input):
numbers=input
# Now convert that list into linked list
dummyRoot = ListNode(0)
ptr = dummyRoot
for number in numbers:
ptr.next = ListNode(number)
ptr = ptr.next ptr = dummyRoot.next
return ptr def listNodeToString(node):
if not node:
return "[]" result = ""
while node:
result += str(node.val) + ", "
node = node.next
return "[" + result[:-2] + "]" def main(): while True:
try: line = [2,4,3]
l1 = stringToListNode(line);
line = [5,6,4]
l2 = stringToListNode(line); ret = Solution().addTwoNumbers(l1, l2) out = listNodeToString(ret);
print(out) #throw
raise StopIteration
except StopIteration:
break if __name__ == '__main__':
main()

加了两个函数整数转链表和链表转整数

Wrong Answer:

Input:
[0]
[0]
Output:
[]
Expected:
[0]

应该是整数转链表时num==0直接跳过了,在前面用number当个标志位就好了

def intToListNode(num):
'''整数转链表,抄袭stringToListNode '''
dummyRoot = ListNode(0)
ptr = dummyRoot
number=-1
while True:
if num == 0:
if number==-1:
ptr.next=ListNode(0)
break
number=num%10
num=num//10 ptr.next = ListNode(number)
ptr = ptr.next ptr = dummyRoot.next
return ptr

提交AC。

总结:学到了链表??既然没学懂,就去弄个链表。

#

class Node(object):
'''节点类''' def __init__(self,data, pnext=None):
'''
data: 节点保存的数据
_next: 保存下一个节点对象
'''
self.data = data
self._next = pnext def __repr__(self):
return str(self.data) class ListNode(object):
'''链表类'''
def __init__(self):
self.head=None
self.lenght=0 def isEmpty(self):
'''判断是否为空'''
return (self.length==0) def append(self,data):
'''增加一个节点'''
item=None
if isinstance(data,Node):
item = data
else:
item = Node(data) #如果头不存在
if not self.head:
self.head = item
self.length = 1
else:
# 如果存在找到末尾然后添加节点
node = self.head
while node._next:
node = node._next
node._next=item
self.length+=1 def delete(self,index):
'''删除一个节点'''
if self.isEmpty():
print("listNode is empty")
return False # 删除头节点
if index == 0:
self.head=self.head._next
self.length-=1
return True j=0
node = self.head
prev = self.head
while node._next and j<index:
prev=node
node=node._next
j+=1 if j==index:
prev._next = node._next
self.length-=1 def getNode(self,index,data=None,update=False):
'''查找节点'''
if self.isEmpty():
print("listNode is empty")
return False
j=0
node=self.head
while node._next and j<index:
node = node._next
j+=1 # 更新
if update:
if j==index:
node.data=data
return return node.data def update(self,index,data):
'''更新节点'''
self.getNode(index,data,True) def getIndex(self,data):
'''查找索引'''
if self.isEmpty():
print("listNode is empty")
return False # 索引列表
index=[] j=0
node=self.head
while node:
if node.data == data:
index.append(j)
node=node._next
j+=1 indexLen=len(index)
if indexLen==0:
return False
elif indexLen==1:
return index[0]
else:
print(" index not only , is list. ")
return index def insert(self,index,data):
'''插入节点'''
if self.isEmpty():
print("listNode is empty, so append data")
index=0
self.head=None
self.append(data)
return True item = None
if isinstance(data,Node):
item = data
else:
item = Node(data) if index==0:
item._next = self.head
self.head = item
self.length += 1 j = 0
node = self.head
prev = self.head
while node._next and j<index:
prev=node
node=node._next
j+=1 if j == index :
item._next = node
prev._next = item
return True def clear(self):
self.head = None
self.length = 0 def __repr__(self):
'''字符串'''
if not self.head:
return ' empty listNode ' s=[]
node = self.head
while node:
s.append(str(node.data))
node = node._next return " -> ".join(s) def __getitem__(self,index):
'''索引取值'''
return self.getNode(index) def __setitem__(self,index,value):
'''设置值'''
print(index)
self.update(index,value) if __name__ == '__main__': # 创建链表
chain=ListNode() # 添加数据
print("add 10 numbers")
for i in range(10,20):
chain.append(i) print(chain) # 查找索引
print("value eq 12 is index = ",end=" ")
print(chain.getIndex(12)) # 更新上面查找的索引
print("update ")
index=chain.getIndex(12)
if isinstance(index,int):
chain.update(index,99) # 再次查找索引
print("again, value eq 12 is index = ",end=" ")
print(chain.getIndex(12)) print(" because listNode is : ")
print(chain) # 删除一个索引
print("delete index 0")
chain.delete(0)
print(chain) # insert
print("insert data")
chain.insert(1,9)
print(chain) # 直接索引获取值
print("use [] get data")
print(chain[3]) # 直接设置值
print("append same value")
chain.append(90)
chain.append(90)
print(chain) # 查找相同值索引
print("search 90 index")
print(chain.getIndex(90))



参考python数据结构之链表(一)

LeetCode 2. add two numbers && 单链表的更多相关文章

  1. LeetCode 2 Add Two Numbers(链表操作)

    题目来源:https://leetcode.com/problems/add-two-numbers/ You are given two linked lists representing two ...

  2. LeetCode(2) || Add Two Numbers && Longest Substring Without Repeating Characters

    LeetCode(2) || Add Two Numbers && Longest Substring Without Repeating Characters 题记 刷LeetCod ...

  3. 【LeetCode-面试算法经典-Java实现】【002-Add Two Numbers (单链表表示的两个数相加)】

    [002-Add Two Numbers (单链表表示的两个数相加)] 原题 You are given two linked lists representing two non-negative ...

  4. [LeetCode] 445. Add Two Numbers II 两个数字相加之二

    You are given two linked lists representing two non-negative numbers. The most significant digit com ...

  5. LeetCode:1. Add Two Numbers

    题目: LeetCode:1. Add Two Numbers 描述: Given an array of integers, return indices of the two numbers su ...

  6. leetcode 题解 Add Two Numbers(两个单链表求和)

    题目: You are given two linked lists representing two non-negative numbers. The digits are stored in r ...

  7. LeetCode第[2]题(Java):Add Two Numbers (链表相加)——Medium

    题目难度:Medium 题目: You are given two non-empty linked lists representing two non-negative integers. The ...

  8. [leetCode][016] Add Two Numbers

    [题目]: You are given two linked lists representing two non-negative numbers. The digits are stored in ...

  9. LeetCode 面试:Add Two Numbers

    1 题目 You are given two linked lists representing two non-negative numbers. The digits are stored in ...

随机推荐

  1. 《Windows核心编程》第3章——深入理解handle

    本文借助windbg来理解程序中的函数如何使用handle对句柄表进行查询的.所以先要开启Win7下Windbg的内和调试功能. 解决win7下内核调试的问题 win7下debug默认无法进行内核调试 ...

  2. 运行Spark提供的计算圆周率的示例程序

    1.启动Spark服务 因为spark是依赖于hadoop提供的分布式文件系统的,所以在启动spark之前,先确保hadoop在正常运行. 在hadoop正常运行的情况下,在master(也就是had ...

  3. RedHat如何关闭防火墙 : http://blog.csdn.net/chongxin1/article/details/76072758

    版本号:RedHat6.5   JDK1.8   Hadoop2.7.3 hadoop  说明:从版本2开始加入了Yarn这个资源管理器,Yarn并不需要单独安装.只要在机器上安装了JDK就可以直接安 ...

  4. Feign 请求拦截器和日志

    Feign 支持请求拦截器,在发送请求前,可以对发送的模板进行操作,例如设置请求头等属性,自定请求拦截器需要实现 feign.RequestInterceptor 接口,该接口的方法 apply 有参 ...

  5. 基于openresty的https配置实践

    最近机器人项目的子项目,由于和BAT中的一家进行合作,人家要求用HTTPS连接,于是乎,我们要改造我们的nginx的配置,加添HTTPS的支持. 当然了,HTTPS需要的证书,必须是认证机构颁发的,这 ...

  6. 【java】标示符

    java的标示符由数字0-9,字母a-zA-Z,_$组成.(java是严格区分大小写的) 标示符的规则: 1.不能以数字开头 2.不能使用关键字 一般的命名规则: 包名:多个单词组成时,所有字母全部小 ...

  7. AXI_LITE源码学习笔记

    AXI_LITE源码学习笔记 1. axi_awready信号的产生 准备接收写地址信号 // Implement axi_awready generation // axi_awready is a ...

  8. GPIO实验

    一.目标:点亮led 1.看原理图:怎样点亮led 2.怎样GPF4输出0/1 a.配置功能  输出/输入/其他功能(中断或者其他) b.设置输出高电平/低电平 操作寄存器--->看芯片手册 A ...

  9. hmaster 启动后自动关闭

    hbase重装后,hmaster却起不来,多次启动也不行,后来发现原因是在zookeeper中之前注册的hmaster仍然存在,系统中只允许一个hmaster运行.解决方法如下: 进入zk客户端,将h ...

  10. InfluxDB 常用命令

    查表: http://192.168.0.200:8086/query?q=select+*+from+telegraf..cpu http://192.168.0.200:8086/query?q= ...