Python:链接lis中的二进制搜索

2024-06-28 22:06:19 发布

您现在位置:Python中文网/ 问答频道 /正文

家庭作业的任务是用binary search方法实现linked list。由于链表本质上是线性的,这看起来确实很奇怪,但是这个想法显然是为了证明一个人能够形成搜索方法并将其连接到LL,本质上只是模拟二进制搜索,因为它的复杂性不会比线性的好。到目前为止,我已经实现了一个简单的链表,以及一个有效的线性搜索方法。在

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))

当前运行binSearch方法时的错误是object does not support indexing。不幸的是,我卡住了。在


Tags: 方法selfnonenodenewgetreturndef