2.实验题2:实现循环双链表的各种基本运算的算法 目的:领会循环双链表存储结构和掌握循环双链表中的各种基本运算算法设计 内容:编写一个程序cdlinklist.py,实现循环双链表的各种运算和整体建表算法(假设循环双链表的元素类型ElemType为int),并在此基础上设计一个程序exp2-2.py完成以下功能。 1)初始化循环双链表h。 2)依次采用尾插法插入1,2,3,4,5元素 3)输出循环双链表h 4)输出循环双链表h的长度 5)判断循环双链表h是否为空 6)输出循环双链表h的第3个元素 7)输出元素 1的位置 8)在第4个元素位置上插入6元素 9)输出循环双链表h 10)删除循环双链表h的第3个元素 11)输出循环双链表h 释放循环双链表h
时间: 2023-11-22 15:56:21 浏览: 143
以下是实现循环双链表的各种基本运算的算法的代码:
```python
class CDNode:
def __init__(self, data=None):
self.data = data
self.prev = None
self.next = None
class CDLinkedList:
def __init__(self):
self.head = CDNode()
self.head.prev = self.head
self.head.next = self.head
self.length = 0
def is_empty(self):
return self.length == 0
def get_length(self):
return self.length
def get_elem(self, index):
if index < 1 or index > self.length:
return None
p = self.head.next
for i in range(1, index):
p = p.next
return p.data
def locate_elem(self, elem):
p = self.head.next
i = 1
while p != self.head and p.data != elem:
p = p.next
i += 1
if p == self.head:
return 0
else:
return i
def insert(self, index, elem):
if index < 1 or index > self.length + 1:
return False
p = self.head
for i in range(1, index):
p = p.next
node = CDNode(elem)
node.prev = p
node.next = p.next
p.next.prev = node
p.next = node
self.length += 1
return True
def delete(self, index):
if index < 1 or index > self.length:
return False
p = self.head
for i in range(1, index):
p = p.next
p.next.prev = p.prev
p.prev.next = p.next
del p
self.length -= 1
return True
def append(self, elem):
node = CDNode(elem)
node.prev = self.head.prev
node.next = self.head
self.head.prev.next = node
self.head.prev = node
self.length += 1
def create_list(self, elem_list):
for elem in elem_list:
self.append(elem)
def clear(self):
while self.head.next != self.head:
self.delete(1)
def print_list(self):
p = self.head.next
while p != self.head:
print(p.data, end=' ')
p = p.next
print()
```
以下是实现实验题2要求的代码:
```python
if __name__ == '__main__':
l = CDLinkedList()
l.create_list([1, 2, 3, 4, 5])
l.print_list() # 1 2 3 4 5
print(l.get_length()) # 5
print(l.is_empty()) # False
print(l.get_elem(3)) # 3
print(l.locate_elem(1)) # 1
l.insert(4, 6)
l.print_list() # 1 2 3 6 4 5
l.delete(3)
l.print_list() # 1 2 6 4 5
l.clear()
l.print_list() #
```
阅读全文