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 添加一个指向链表尾部的属性.)
为 LinkedList 添加类似 Python 自带列表实现 list 中的 append, pop, insert 方法
答案:1 悬赏:50 手机版
解决时间 2021-02-28 15:20
- 提问者网友:浪荡绅士
- 2021-02-28 03:38
最佳答案
- 五星知识达人网友:雪起风沙痕
- 2021-02-28 03:56
写了个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)
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)
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯