Python实现链表

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/mxj588love/article/details/80974801
class LinkedList:

    def __init__(self):
        self.size = 0
        self.head = Node
        pass

    def addItem(self, obj):
        newNode = Node(obj)
        if self.size <= 0:
            self.head = newNode
        else:
            newNode.next = self.head
            self.head = newNode
        self.size += 1

    def list(self):
        current = self.head
        while current != None:
            print current.data
            current = current.next

    def deleteHead(self):
        if self.size <= 0:
            return None
        self.head = self.head.next
        self.size -= 1

    def delete(self, index):

        if self.size <= 0:
            return None

        if index == 0:
            self.head = self.head.next
            return

        j = 0
        #保存当前节点
        current = self.head
        #保存前面的节点
        prev = self.head
        while current.next:
            if j == index:
                prev.next = current.next
                self.size -= 1
                break
            prev = current
            current = current.next
            j+=1

    #获得指定索引出的节点
    def get(self, index):
        if self.size <= 0:
            return None
        current = self.head
        j = 0
        while current :
            if j == index:
                return current
            current = current.next
            j+=1

    #获得指定值处的索引
    def getIndex(self, value):
        current = self.head
        j = 0
        while current:
            if value == current.data:
                return j
            current = current.next
            j+=1

if __name__ == '__main__':
    linkedlist = LinkedList()
    linkedlist.addItem("a")
    linkedlist.addItem("b")
    linkedlist.addItem("c")
    linkedlist.addItem("d")
    linkedlist.addItem("e")

    #linkedlist.deleteHead()
    #linkedlist.list()
    #linkedlist.delete(2)

    #linkedlist.list()
    #print linkedlist.get(4).data
    #print linkedlist.getIndex("e")
展开阅读全文

没有更多推荐了,返回首页