天天看點

python實作雙連結清單

class Node:
    def __init__(self, item):
        self.elem = item
        self.next = None
        self.pre = None


class DoubleLinkList:
    def __init__(self, node=None):
        self._head = node

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

    def length(self):
        """
        擷取長度,同單連結清單的擷取長度
        :return:
        """
        count = 0
        cur = self._head
        while cur is not None:
            count += 1
            cur = cur.next
        return count

    def travel(self):
        """
        周遊,同單連結清單的周遊
        :return:
        """
        cur = self._head
        while cur is not None:
            print(cur.elem, end=" ")
            cur = cur.next
        print("")

    def add(self, item):
        """
        添加節點
        :param item:
        :return:
        """
        node = Node(item)
        node.next = self._head
        # node.next.pre = node
        # self._head = node
        # 或者答案不為1
        self._head = node
        node.next.pre = node

    def append(self, item):
        """
        :param item:
        :return:
        """
        node = Node(item)
        if self.is_empty():
            self._head = node
        else:
            cur = self._head
            while cur.next is not None:
                cur = cur.next
            cur.next = node
            node.pre = cur

    def insert(self, pos, item):
        if pos <= 0:
            self.add(item)
        elif pos > (self.length() - 1):
            self.append(item)
        else:
            cur = self._head
            count = 0
            while count < pos:
                count += 1
                cur = cur.next
            node = Node(item)
            node.next = cur
            node.pre = cur.pre
            # 斷開原來的連結
            cur.pre.next = node
            cur.pre = node

    def search(self, item):
        """
        查找節點
        :param item:
        :return:
        """
        cur = self._head
        while cur is not None:
            if cur.elem == item:
                return True
            else:
                cur = cur.next
        return False

    def delete(self, item):
        cur = self._head
        while cur is not None:
            if cur.elem == item:
                if cur == self._head:
                    self._head = cur.next
                    # 判斷連結清單是否隻有一個節點
                    if cur.next:
                        cur.next.pre = None
                else:
                    cur.pre.next = cur.next
                    # 判斷是否是結尾的節點
                    if cur.next:
                        cur.next.pre = cur.pre
                break
            else:
                cur = cur.next