单双链表实现代码用python怎么写
时间: 2024-04-11 14:17:00 浏览: 91
python单链表实现代码实例
以下是单链表的实现代码:
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def add_node(self, data):
new_node = Node(data)
if not self.head:
self.head = new_node
else:
current_node = self.head
while current_node.next:
current_node = current_node.next
current_node.next = new_node
def delete_node(self, data):
current_node = self.head
prev_node = None
while current_node:
if current_node.data == data:
if prev_node:
prev_node.next = current_node.next
else:
self.head = current_node.next
return True
prev_node = current_node
current_node = current_node.next
return False
def print_list(self):
current_node = self.head
while current_node:
print(current_node.data)
current_node = current_node.next
以下是双链表的实现代码:
class Node:
def __init__(self, data):
self.data = data
self.next = None
self.prev = None
class DoublyLinkedList:
def __init__(self):
self.head = None
def add_node(self, data):
new_node = Node(data)
if not self.head:
self.head = new_node
else:
current_node = self.head
while current_node.next:
current_node = current_node.next
current_node.next = new_node
new_node.prev = current_node
def delete_node(self, data):
current_node = self.head
while current_node:
if current_node.data == data:
if current_node.prev:
current_node.prev.next = current_node.next
else:
self.head = current_node.next
if current_node.next:
current_node.next.prev = current_node.prev
return True
current_node = current_node.next
return False
def print_list(self):
current_node = self.head
while current_node:
print(current_node.data)
current_node = current_node.next
阅读全文