完成家庭作业,并使用binary search
方法实施class Node:
def __init__(self, cargo):
self.cargo = cargo
self.next = None
def get_data(self):
return self.cargo
def get_next(self):
return self.next
class LinkedList:
def __init__(self):
self.head = None
self.tail = None
def add(self, cargo):
new_node = Node(cargo)
if self.head == None:
self.head = new_node
if self.tail != None:
self.tail.next = new_node
self.tail = new_node
def PrintList(self):
node = self.head
while node != None:
print(node.cargo)
node = node.next
def length(self):
current = self.head
count = 0
while current != None:
count = count + 1
current = current.get_next()
return count
def linSearch(self, cargo):
current = self.head
found = False
while current and found is False:
if current.get_data() == cargo:
found = True
else:
current = current.get_next()
return found
def binSearch(self, cargo):
LL = LinkedList
low = 0
high = LL.length(self)-1
while low <= high:
mid = (low+high)//2
if self[mid] > cargo:
high = mid-1
elif self[mid] < cargo:
low = mid+1
else:
return mid
return -1
LL = LinkedList()
LL.add(1)
LL.PrintList()
print(LL.linSearch(2))
print(LL.binSearch(1))
。由于链表本质上是线性的,这看起来确实很奇怪,但是这个想法显然是为了表明一个人能够形成搜索方法并将其连接到LL,实际上只是模拟二进制搜索,因为它的复杂性不会比那更好。线性的。到目前为止,我已经实现了一个简单的链表,以及一个有效的线性搜索方法。
binSearch
运行object does not support indexing
方法时的当前错误是var childElement = document.getElementById("myChildElement");
document.getElementById("myElement").removeChild(childElement);
。不幸的是,我被困住了。