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