美文网首页
双向链表python实现

双向链表python实现

作者: sttech | 来源:发表于2019-04-23 13:43 被阅读0次

python 双向链表实现

class Node(object):
    def __init__(self,item):
        self.next = None
        self.prev = None
        self.item = item

双向链表实现

双向链表
class DoubleLinkList(object):
    def __init__(self):
        self._head = None

    def is_empty(self):
        return  self._head == None

    def length(self):
        current = self._head
        count = 0
        while current.next != None:
            current = current.next
            count += 1
        return  count

    def travel(self):
        if self.is_empty():
            return
        current = self._head
        strs = 'item :' + str(current.item)
        while current.next != None:
            current = current.next
            strs += ', item :' + str(current.item)
        print(strs)
        return  strs

链表头部添加

    def add(self,item):
        node = Node(item)
        node.next = self._head
        self._head = node

链表尾部添加

    def append(self,item):
        node = Node(item)
        current = self._head
        while current.next != None:
            current = current.next
        current.next = node
        node.next = None

插入

插入
    def insert(self,index,item):
        if self.is_empty() :
            self.add(item)
        elif index < 1:
            self.add(item)
        elif index > self.length() - 1  :
            self.append(item)
        else:
            node = Node(item)
            preNode = self._head
            count = 0
            while count < index - 1 :
                preNode = preNode.next
                count += 1
            node.next = preNode.next
            preNode.next = node

删除

删除
    def remove(self,item):
        if self.is_empty():
            return
        current = self._head
        if current.item == item:
            self._head = current.next

        else:
            while current.next != None:
                preNode = current
                current = current.next
                if current.item == item:
                    preNode.next = current.next

查询结点

    def search(self,item):
        current = self._head
        if current.item == item:
            return current
        while current.next != None:
            current = current.next
            if current.item == item:
                return  current


相关文章

网友评论

      本文标题:双向链表python实现

      本文链接:https://www.haomeiwen.com/subject/btkvgqtx.html