为 LinkedList 添加类似 Python 自带列表实现 list 中的 append, pop, insert 方法
1.为LinkedList添加类似Python自带列表实现list中的append,pop,insert方法.分别给出你实现的这三个方法的时间复杂度.classNode:...
1.为 LinkedList 添加类似 Python 自带列表实现 list 中的 append, pop, insert 方法. 分别给出你实现的这三个方法的时间复杂度.
class Node:
def __init__(self,data):
self.data = data
self.next = None
def getData(self):
return self.data
def getNext(self):
return self.next
def setData(self,newdata):
self.data = newdata
def setNext(self,newnext):
self.next = newnext
class LinkedList:
def __init__(self):
self.head = None
def isEmpty(self):
return self.head == None
def add(self,item):
temp = Node(item)
temp.setNext(self.head)
self.head = temp
def size(self):
current = self.head
count = 0
while current != None:
count += 1
current = current.getNext()
return count
def search(self,item):
current = self.head
found = False
while current != None and not found:
if current.getData() == item:
found = True
else:
current = current.getNext()
return found
def remove(self,item):
current = self.head
previous = None
found = False
while current != None and not found:
if current.getData() == item:
found = True
else:
previous = current
current = current.getNext()
if found:
if previous == None:
self.head = current.getNext()
else:
previous.setNext(current.getNext())
2.在之前的一题中, 你很可能实现的是一个复杂度为 $O(n)$ 的 append 方法. 如何修改程序, 使得可以使其复杂度为 $O(1)$? (提示: 为 LinkedList 添加一个指向链表尾部的属性.) 展开
class Node:
def __init__(self,data):
self.data = data
self.next = None
def getData(self):
return self.data
def getNext(self):
return self.next
def setData(self,newdata):
self.data = newdata
def setNext(self,newnext):
self.next = newnext
class LinkedList:
def __init__(self):
self.head = None
def isEmpty(self):
return self.head == None
def add(self,item):
temp = Node(item)
temp.setNext(self.head)
self.head = temp
def size(self):
current = self.head
count = 0
while current != None:
count += 1
current = current.getNext()
return count
def search(self,item):
current = self.head
found = False
while current != None and not found:
if current.getData() == item:
found = True
else:
current = current.getNext()
return found
def remove(self,item):
current = self.head
previous = None
found = False
while current != None and not found:
if current.getData() == item:
found = True
else:
previous = current
current = current.getNext()
if found:
if previous == None:
self.head = current.getNext()
else:
previous.setNext(current.getNext())
2.在之前的一题中, 你很可能实现的是一个复杂度为 $O(n)$ 的 append 方法. 如何修改程序, 使得可以使其复杂度为 $O(1)$? (提示: 为 LinkedList 添加一个指向链表尾部的属性.) 展开
1个回答
展开全部
写了个insert
def insert(self,index,item):
previous=None
current=self.head
count=0
temp=Node(item)
if index>self.size():
print "out index"
elif index==0:
temp.setNext(current)
self.head=temp
else:
while index:
index-=1
previous=current
current=current.getNext()
previous.setNext(temp)
temp.setNext(current)
更多追问追答
追问
请问前两个的要怎么写
追答
自己想啊,都差不多的过程。就算我告诉你你以后还是不会写。
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询