python利用头插法单向循环链表
时间: 2023-10-12 16:20:59 浏览: 85
头插法单链表
以下是Python代码示例,实现了头插法单向循环链表:
```python
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def add_to_front(self, data):
new_node = Node(data)
if self.head is None:
self.head = new_node
new_node.next = self.head
else:
curr_node = self.head
while curr_node.next != self.head:
curr_node = curr_node.next
curr_node.next = new_node
new_node.next = self.head
self.head = new_node
def print_list(self):
if self.head is None:
print("List is empty")
else:
curr_node = self.head
while True:
print(curr_node.data, end=" ")
curr_node = curr_node.next
if curr_node == self.head:
break
print()
```
使用示例:
```python
ll = LinkedList()
ll.add_to_front(3)
ll.add_to_front(2)
ll.add_to_front(1)
ll.print_list() # 1 2 3
```
阅读全文