Python链表的实现

还有如下功能未有实现:

  1. insert
  2. pop
  3. index
    python中的列表是基于数组实现的

class Node:
    def __init__(self, initdata):
        self.data = initdata
        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 UnorderedList:
    def __init__(self):
        self.head = None

    def isEmpty(self):
        return not self.head

    def add(self, item):
        """
        分三步走:
        创建一个新的节点
        将现在的头节点设置为下一节点
        将新节点设置为头节点
        :param item:
        :return:
        """
        temp = Node(item)
        temp.setNext(self.head)
        self.head = temp

    """
    链表遍历技术
    """
    def length(self):
        count = 0
        current = self.head
        while current:
            count += 1
            current = current.getNext()
        return count

    def search(self, item):
        current = self.head
        while current:
            if current.getData == item:
                return True
            current = current.getNext
        return False

    def remove(self, item):
        current = self.head
        previous = None
        while current:
            if current.getData == item:
                if not previous:
                    self.head = current.getNext
                else:
                    previous.setNext(current.getNext)
            else:
                previous = current
                current = current.getNext

    def append(self, item):
        current = self.head
        while current:
            current = current.getNext
        current.setNext(Node(item))

你可能感兴趣的:(python,链表,开发语言)