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. GPIO实验

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

  2. 使用C#调用PI-SDK进行基于PI的开发

    一.概述 PI-SDK(Plant Information Software Develop Kit)是OSI公司提供的基于面向对象的访问PI数据库的软件开发工具包,它可以对以下数据库进行读写: ²  ...

  3. Azure PowerShell (15) 批量导出Azure ASM/ARM VM信息

    <Windows Azure Platform 系列文章目录> 客户又提出新的需求,需要知道所有订阅下的虚拟机数量.运行情况等信息. 我花了点时间,写了一个PowerShell脚本,发布到 ...

  4. python selenium right click on an href and choose Save link as... on Chrome.

    From:https://stackoverflow.com/questions/42781483/right-click-on-an-href-and-choose-save-link-as-in- ...

  5. 【java】之Method和Field反射获取和设置属性值

    package com.javaluna.reflect; import java.lang.reflect.Field; import java.lang.reflect.Method; impor ...

  6. C++11--右值引用(Perfect Forwarding)

    /* * 右值引用 2: Perfect Forwarding */ void foo( boVector arg ); // boVector既有移动构造又有拷贝构造 template< ty ...

  7. webpack学习总结(一)

    * webpack安装 1. 安装最新node,node自带npm包管理器: 2. 全局模式安装webpack(只有将webpack在全局模式下安装才能在命令行直接通过webpack执行命令) $np ...

  8. 史上最全Spring面试71题与答案

    1.什么是spring? Spring是个java企业级应用的开源开发框架.Spring主要用来开发Java应用,但是有些扩展是针对构建J2EE平台的web应用.Spring框架目标是简化Java企业 ...

  9. php给app写接口进行接口的加密

    <?php/**inc解析接口客户端接口传输规则:1.用cmd参数(base64)来动态调用不同的接口,接口地址统一为 http://a.lovexpp.com2.将要传过来的参数组成一个数组, ...

  10. centos6.5虚拟机快照技术

    一.查看现有磁盘镜像格式与转换 查看磁盘格式 [root@localhost ~]# qemu-img info /var/lib/libvirt/images/centos7.img image: ...