LeetCode 2. add two numbers && 单链表
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))
LeetCode 2. add two numbers && 单链表的更多相关文章
- LeetCode 2 Add Two Numbers(链表操作)
题目来源:https://leetcode.com/problems/add-two-numbers/ You are given two linked lists representing two ...
- LeetCode(2) || Add Two Numbers && Longest Substring Without Repeating Characters
LeetCode(2) || Add Two Numbers && Longest Substring Without Repeating Characters 题记 刷LeetCod ...
- 【LeetCode-面试算法经典-Java实现】【002-Add Two Numbers (单链表表示的两个数相加)】
[002-Add Two Numbers (单链表表示的两个数相加)] 原题 You are given two linked lists representing two non-negative ...
- [LeetCode] 445. Add Two Numbers II 两个数字相加之二
You are given two linked lists representing two non-negative numbers. The most significant digit com ...
- LeetCode:1. Add Two Numbers
题目: LeetCode:1. Add Two Numbers 描述: Given an array of integers, return indices of the two numbers su ...
- leetcode 题解 Add Two Numbers(两个单链表求和)
题目: You are given two linked lists representing two non-negative numbers. The digits are stored in r ...
- LeetCode第[2]题(Java):Add Two Numbers (链表相加)——Medium
题目难度:Medium 题目: You are given two non-empty linked lists representing two non-negative integers. The ...
- [leetCode][016] Add Two Numbers
[题目]: You are given two linked lists representing two non-negative numbers. The digits are stored in ...
- LeetCode 面试:Add Two Numbers
1 题目 You are given two linked lists representing two non-negative numbers. The digits are stored in ...
随机推荐
- SQL优化之count(*),count(列)
一.count各种用法的区别 1.count函数是日常工作中最常用的函数之一,用来统计表中数据的总数,常用的有count(*),count(1),count(列).count(*)和count(1)是 ...
- [转]Python中yield的解释
转自: http://python.jobbole.com/83610/ 本文作者: 伯乐在线 - wklken .未经作者许可,禁止转载!欢迎加入伯乐在线 专栏作者. 翻译 来源于stackover ...
- mysql 删除数据库中所有的表中的数据,只删database下面所有的表。
select concat('drop table ',table_name,';') from TABLES where table_schema='数据库名称'; select concat('t ...
- Vim插件集合
插件Nerdtree实现浏览文件系统并打开文件或目录,在window中是非常不错的插件,但是在Ubuntu中这个插件就是一坑,特别提示,且无解.若在Ubuntu中使用目录浏览插件,建议使用其他插件,如 ...
- 关于java多线程理解到集群分布式和网络设计的浅析
对于JAVA多线程的应用非常广泛,现在的系统没有多线程几乎什么也做不了,很多时候我们在何种场合如何应用多线程成为一种首先需要选择的问题, 另外关于java多线程的知识也是非常的多,本文中先介绍和说明一 ...
- jquery add() 和js add()
HTML DOM add() 方法 HTML DOM Select 对象 定义和用法 add() 方法用于向 <select> 添加一个 <option> 元素. 语法 sel ...
- [UE4]Set Skeletal Mesh,在蓝图中设置骨骼模型
- KPPW2.7 漏洞利用--文件上传
KPPW2.7 漏洞利用----文件上传 文件上传导致任意代码执行 搭建环境 1,集成环境简单方便,如wamp,phpstudy.... 2,KPPW v2.7源码一份(文末有分享)放到WWW目录下面 ...
- [SQL]卸载数据库清理注册表方法regedit
.打开注册表. 开始——运行——regedit——确定 .然后找到下面的文件夹,删除掉: HKEY_CURRENT_USER\ Software\ Microsoft\ Microsoft SQL S ...
- 01-Socket服务器
package com.day1; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOExc ...