需要设计一个单链表结构,该链表结构数据域存储整数。 编写函数实现基本运算方法。基本运算方法应包括创建链表、销毁链表、求链表长度、 求链表某一位置节点的值、查找值为 x 的节点所在位置、新增节点、插入节点、删除节点。
时间: 2024-09-25 19:06:45 浏览: 37
为了设计一个单链表结构,你需要首先定义一个Node类,它包含两个属性:一个整数值和一个指向下一个节点的引用。然后你可以定义一个LinkedList类,包含链表的操作方法:
```python
class Node:
def __init__(self, value):
self.value = value
self.next = None
class LinkedList:
def __init__(self):
self.head = None
self.length = 0
# 创建链表
def create_list(self):
self.head = None
# 销毁链表
def destroy_list(self):
self.head = None
self.length = 0
# 求链表长度
def get_length(self):
current = self.head
while current is not None:
self.length += 1
current = current.next
return self.length
# 获取某位置节点的值
def get_node_value(self, position):
if position < 0 or position >= self.length:
raise IndexError("Position out of range")
current = self.head
for _ in range(position):
current = current.next
return current.value
# 查找值为x的节点
def find_node_by_value(self, x):
current = self.head
position = 0
while current is not None:
if current.value == x:
return position
current = current.next
position += 1
return -1 # 如果未找到,返回-1
# 新增节点
def add_node(self, value):
new_node = Node(value)
if not self.head:
self.head = new_node
else:
current = self.head
while current.next:
current = current.next
current.next = new_node
self.length += 1
# 插入节点
def insert_node(self, position, value):
if position < 0 or position > self.length:
raise IndexError("Invalid position")
new_node = Node(value)
if position == 0:
new_node.next = self.head
self.head = new_node
else:
current = self.head
for _ in range(position - 1):
current = current.next
new_node.next = current.next
current.next = new_node
self.length += 1
# 删除节点
def delete_node(self, position):
if position < 0 or position >= self.length:
raise IndexError("Invalid position")
if position == 0:
self.head = self.head.next
else:
current = self.head
for _ in range(position - 1):
current = current.next
current.next = current.next.next
if self.head is None:
self.length = 0
else:
self.length -= 1
阅读全文