天天看點

python 單連結清單頭插尾插python 單連結清單頭插尾插

python 單連結清單頭插尾插

資料結構算法非常薄弱,查缺補漏,看了書後想實作單連結清單的頭插和尾插,用python實作,看到一篇文章已經實作了頭插https://www.php.cn/python-tutorials-416272.html

自己想了下,寫了一個尾插

class Node:

    def __init__(self, data, nextNode=None):
        self.data = data
        self.nextNode = nextNode

    def getData(self):
        return self.data

    def setData(self, val):
        self.data = val

    def getNextNode(self):
        return self.nextNode

    def setNextNode(self, val):
        self.nextNode = val


class LinkedList:

    def __init__(self, head=None):
        self.head = head
        self.size = 0
        self.tail = head

    def getSize(self):
        return self.size

    def addNodeHead(self, data):
        newNode = Node(data, self.head)
        self.head = newNode
        self.size += 1
        return True
    def addNodeTail(self, data):        
        newNode = Node(data)
        if self.head == None:
            self.head = newNode
            self.tail = self.head
        else:
            self.tail.nextNode = newNode
            self.tail = newNode

        self.size += 1
        return True
    def printNode(self):
        curr = self.head
        while curr:
            print(curr.data)
            curr = curr.getNextNode()


myList = LinkedList()
print("Inserting")
#myList.addNodeHead(5)
#(myList.addNodeHead(15))
#(myList.addNodeHead(25))
#print("Printing")

(myList.addNodeTail(5))
(myList.addNodeTail(15))
(myList.addNodeTail(25))

myList.printNode()
print("Size")
print(myList.getSize())
···