双向链表的插入和删除代码
时间: 2023-05-26 11:03:27 浏览: 110
1. 双向链表的插入代码:
```python
class Node:
def __init__(self, data):
self.data = data
self.next = None
self.prev = None
class DoublyLinkedList:
def __init__(self):
self.head = None
def push(self, new_data):
new_node = Node(new_data)
new_node.next = self.head
if self.head is not None:
self.head.prev = new_node
self.head = new_node
def insertAfter(self, prev_node, new_data):
if prev_node is None:
return
new_node = Node(new_data)
new_node.next = prev_node.next
prev_node.next = new_node
new_node.prev = prev_node
if new_node.next is not None:
new_node.next.prev = new_node
def append(self, new_data):
new_node = Node(new_data)
new_node.next = None
if self.head is None:
new_node.prev = None
self.head = new_node
return
last = self.head
while last.next:
last = last.next
last.next = new_node
new_node.prev = last
return
def printList(self, node):
while node is not None:
print(node.data),
node = node.next
```
上述代码中,DoublyLinkedList类有三种插入方式,分别是push(), insertAfter()和append()方法,分别用于在链表头部、指定节点后和链表尾部插入节点。
2. 双向链表的删除代码:
```python
class Node:
def __init__(self, data):
self.data = data
self.next = None
self.prev = None
class DoublyLinkedList:
def __init__(self):
self.head = None
def push(self, new_data):
new_node = Node(new_data)
new_node.next = self.head
if self.head is not None:
self.head.prev = new_node
self.head = new_node
def deleteNode(self, dele):
if self.head is None or dele is None:
return
if self.head == dele:
self.head = dele.next
if dele.next is not None:
dele.next.prev = dele.prev
if dele.prev is not None:
dele.prev.next = dele.next
def printList(self, node):
while node is not None:
print(node.data),
node = node.next
```
上述代码中,DoublyLinkedList类有一个deleteNode()方法,用于删除指定节点。通过该方法实现双向链表的删除操作。
阅读全文