python 双链表
时间: 2023-12-05 10:41:23 浏览: 84
python双向链表实现实例代码
5星 · 资源好评率100%
双链表是一种链式数据结构,每个节点有两个指针,一个指向前一个节点,一个指向后一个节点。相比于单链表,双链表可以双向遍历,查找效率更高。以下是Python实现双链表的代码:
```python
class Node(object):
def __init__(self, val, p=0):
self.data = val
self.next = p
self.prev = p
class DoubleLinkList(object):
def __init__(self):
self.head = 0
def isEmpty(self):
return self.head == 0
def length(self):
p = self.head
length = 0
while p != 0:
length += 1
p = p.next
return length
def travel(self):
p = self.head
while p != 0:
print(p.data)
p = p.next
def add(self, val):
node = Node(val)
if self.isEmpty():
self.head = node
else:
node.next = self.head
self.head.prev = node
self.head = node
def append(self, val):
node = Node(val)
if self.isEmpty():
self.head = node
else:
p = self.head
while p.next != 0:
p = p.next
p.next = node
node.prev = p
def insert(self, pos, val):
if pos <= 0:
self.add(val)
elif pos > self.length() - 1:
self.append(val)
else:
node = Node(val)
p = self.head
count = 0
while count < pos - 1:
count += 1
p = p.next
node.prev = p
node.next = p.next
p.next.prev = node
p.next = node
def remove(self, val):
if self.isEmpty():
return
p = self.head
if p.data == val:
if p.next == 0:
self.head = 0
else:
p.next.prev = 0
self.head = p.next
return
while p.next != 0:
if p.next.data == val:
p.next = p.next.next
if p.next != 0:
p.next.prev = p
return
p = p.next
```
阅读全文