python insertLink 链表前中后插入

class Node:#创建链表
    def __init__(self, dataval=None):
        self.dataval = dataval
        self.nextval = None

class SLinkedList:
    def __init__(self):#创建链表
        self.headval = None

    def listVal(self):#遍历链表列表
        val = self.headval
        while val is not None:
            print(val.dataval)
            val = val.nextval

    def FromHead(self, insertdata):#插入链接列表中,插入头部位置
        NewNode = Node(insertdata)  #‘创建一个节点’
        NewNode.nextval = self.headval  #‘这个创建节点的下一个节点是原来头节点’
        self.headval = NewNode  #‘把这个新节点赋为现在头节点’

    def FromEnd(self, insertdata):#插入链接列表中,插入尾部位置
        NewNode = Node(insertdata)  #‘创建一个节点’
        if self.headval is None:  #‘判断如果原来头节点为空,直接赋新节点为头节点’
            self.headval = NewNode
            return

        end = self.headval  #‘把头节点赋为end节点’
        while end.nextval:  #'从前往后找最后一个点击'
            end = end.nextval
        end.nextval=NewNode  #‘把新节点赋为最后一个节点’

    def Inbetween(self,Middlenode,insertdata):#插入链接列表中,中间位置
        NewNode = Node(insertdata)
        if Middlenode is None:
            return

        NewNode.nextval = Middlenode.nextval  #'中间节点的下一个节点是插入节点'
        Middlenode.nextval = NewNode #‘查插入节点赋给中间节点的下一个节点’


list = SLinkedList()
list.headval = Node("Mon")
e2 = Node("Tue")
e3 = Node("Wed")
list.headval.nextval = e2
e2.nextval = e3
list.listVal()

print("................")

list.FromHead("Sun")
list.listVal()
print("................")

list.FromEnd("Fri")
list.listVal()
print("................")


list.Inbetween(list.headval.nextval.nextval.nextval,"Thur")
list.listVal()

运行输出:

Mon
Tue
Wed
................
Sun
Mon
Tue
Wed
................
Sun
Mon
Tue
Wed
Fri
................
Sun
Mon
Tue
Wed
Thur
Fri
 

你可能感兴趣的:(算法逻辑,python基础,链表,python,数据结构)