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

 

posted on 2018-01-09 11:19  可可_小虾米  阅读(411)  评论(0编辑  收藏  举报

导航