Python实现链表

一、链表的基本结构单元定义——Node类的实现


class Node:
    def __init__(self, x):
        self.data = x
        self.next = None

    def getData(self):
        return self.data

    def getNext(self):
        return self.next

    def setNext(self, newNext):
        self.next = newNext

二、链表的实现

链表是中每一个节点都通过显示的引用指向下一个节点,只需要知道第一个节点的位置,后面的每一个节点都可以通过引用找到。因此,链表类UnorderedList只需要包含指向第一个节点的引用。

2.1 链表的初始化

empty.png
def __init__(self):
        # head为指向第一个节点的引用,并非一个Node
        self.head = None

2.2 链表添加操作

add.png
 def add(self, item):

        # 顺序不能乱,栓新绳,解旧绳
        temp = Node(item)
        temp.setNext(self.head)
        self.head = temp

2.3 链表的删除操作

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

\

UnorderedList实现

class UnorderedList:
    def __init__(self):
        # head为指向第一个节点的引用,并非一个Node
        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 length(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 remvove(self, item):
        current = self.head
        previous = None
        found = False
        while not found:
            if current.getData == item:
                found = True
            else:
                previous = current
                current = current.getNext()
        if previous == None:
            self.head = current.getNext()
        else:
            previous.setNext(current.getNext())

你可能感兴趣的:(Python实现链表)