利用python创造链表,实现部分链表功能
链表主要由链表体和节点构成,链表体提供框架,节点承载数据及提供链接功能。
代码示例:
class Node:
def __init__(self,dataval=None):
self.dataval=dataval
self.nextval=None
def nodeprint(self):
return str(self.dataval)
class Linked_lists:
def __init__(self):
self.headval=None
def listprint(self):
printval=self.headval
while printval is not None:
print(printval.dataval)
printval=printval.nextval
def atBegin(self,newdata):
NewNode=Node(newdata)
NewNode.nextval=self.headval
self.headval=NewNode
def atEnd(self,newdata):
printval=self.headval
NewNode=Node(newdata)
if printval is None:
self.headval=NewNode
return
LastNode=self.headval
while LastNode.nextval:
LastNode=LastNode.nextval
LastNode.nextval=NewNode
def Insert(self,newData,position):
if position is None:
return
newNode=Node(newData)
newNode.nextval=position.nextval
position.nextval=newNode
def RemoveNode(self, Removekey):
HeadVal = self.headval
if (HeadVal is not None):
if (HeadVal.dataval == Removekey):
self.headval = HeadVal.nextval
HeadVal = None
return
while (HeadVal is not None):
if HeadVal.dataval == Removekey:
break
prev = HeadVal
HeadVal = HeadVal.nextval
if (HeadVal == None): #未找到目标值返回None
return
prev.nextval = HeadVal.nextval #跳过删除节点链接下一点
HeadVal = None #清除删除点信息
node1=Node(1)
node2=Node(2)
node3=Node(3)
list1=Linked_lists()
list1.headval=node1
node1.nextval=node2
node2.nextval=node3
list1.atEnd(8)
list1.atBegin(0)
list1.RemoveNode(2)
list1.listprint()
参考自:https://www.tutorialspoint.com/python/python_linked_lists.htm