【python中单链表的实现】——包括初始化、创建、逆序、遍历等

# coding=utf-8

class mynode(object):
    def __init__(self, data, nextnode = None):
        self.data = data
        self.next = nextnode

class myLink(object):
    def __init__(self, datanode):
        node = mynode(datanode, None)
        self.header = node
        self.prev = None
    
    def createLink(self, datalist):
        tempheader = self.header
        for i in range(0, len(datalist)):
            node = mynode(datalist[i])
            tempheader.next = node
            tempheader = tempheader.next
    
    def printLink(self):
        tempheader = self.header
        while tempheader != None:
            print tempheader.data
            tempheader = tempheader.next
            

    def reversLink(self):
        reverseheader = None
        tempheader = self.header
        tempnext = tempheader.next
        while tempheader != None:
            tempheader.next = reverseheader
            reverseheader = tempheader
            tempheader = tempnext
            if tempheader != None:
                tempnext = tempheader.next
#         tempheader.next = reverseheader
#         reverseheader = tempheader
        self.header = reverseheader
                
if __name__ == "__main__":
    mylink = myLink(1)
    mylink.printLink()
    print "------------"
    mylink.createLink([2,3,4,5])
    mylink.printLink()
    print "------------"
    mylink.reversLink()
    mylink.printLink()
            
            

 

转载于:https://www.cnblogs.com/keke-xiaoxiami/p/8250531.html

你可能感兴趣的:(【python中单链表的实现】——包括初始化、创建、逆序、遍历等)