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