编写一个结点类,该类中含有结点的定义和初始化,编写一个只带有表尾变量rear的循环单链表类,该类中至少包含以下基本操作,初始化,求表的长度,首段插入结点,将新结点插入到链表第i个位置(假设头结点位置为0),删除最后一个结点,输出所有结点中的元素,通过以下步骤测试基本操作的实现实现是否正确,创建一个类的实例,实例名Lclist_姓名,将值为a,a*10,a*100,a*1000的结点依次从首端链入单链表中,输出表中元素,获取该链表长度,将值为2023的结点插入至表中第3个位置,将最后一个元素删除,输出表中元素
时间: 2023-05-26 09:05:36 浏览: 102
带表头结点的线性链表的实现 源代码
结点类:
```python
class Node:
def __init__(self, data):
self.data = data
self.next = None
```
循环单链表类:
```python
class LCLNode:
def __init__(self):
self.rear = None
def is_empty(self):
return self.rear == None
def length(self):
if self.rear == None:
return 0
count = 1
cur = self.rear.next
while cur != self.rear:
cur = cur.next
count += 1
return count
def add(self, data):
node = Node(data)
if self.rear == None:
self.rear = node
node.next = self.rear
else:
node.next = self.rear.next
self.rear.next = node
def insert(self, i, data):
if i < 0 or i >= self.length():
raise IndexError('index out of range')
node = Node(data)
count = 0
cur = self.rear
while cur.next != self.rear:
if count == i:
node.next = cur.next
cur.next = node
return
cur = cur.next
count += 1
if count == i:
node.next = cur.next
cur.next = node
def delete_last(self):
if self.rear == None:
raise Exception('list is empty')
elif self.rear.next == self.rear:
self.rear = None
else:
cur = self.rear.next
while cur.next != self.rear:
cur = cur.next
cur.next = self.rear.next
self.rear = cur
def print_all(self):
if self.rear == None:
print('list is empty')
return
cur = self.rear.next
while cur != self.rear:
print(cur.data, end=' ')
cur = cur.next
print(cur.data)
```
测试:
```python
list_a = LCLNode()
list_a.add('a')
list_a.add('a' * 10)
list_a.add('a' * 100)
list_a.add('a' * 1000)
list_a.print_all() # a aaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
print(list_a.length()) # 4
list_a.insert(2, 2023)
list_a.print_all() # a aaaaaaaaaa 2023 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
list_a.delete_last()
list_a.print_all() # a aaaaaaaaaa 2023 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
```
阅读全文