编写一个线性表的计算在单链表中的实现的代码
时间: 2024-02-11 10:04:05 浏览: 72
线性表的单链表实现
3星 · 编辑精心推荐
下面是一个基于单链表的线性表实现的示例代码:
```python
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
self.size = 0
def append(self, data):
new_node = Node(data)
if self.head is None:
self.head = new_node
else:
current = self.head
while current.next is not None:
current = current.next
current.next = new_node
self.size += 1
def get(self, index):
if index < 0 or index >= self.size:
return None
current = self.head
for i in range(index):
current = current.next
return current.data
def insert(self, index, data):
if index < 0 or index > self.size:
return False
new_node = Node(data)
if index == 0:
new_node.next = self.head
self.head = new_node
else:
current = self.head
for i in range(index - 1):
current = current.next
new_node.next = current.next
current.next = new_node
self.size += 1
return True
def remove(self, data):
current = self.head
previous = None
while current is not None:
if current.data == data:
if previous is None:
self.head = current.next
else:
previous.next = current.next
self.size -= 1
return True
else:
previous = current
current = current.next
return False
```
上面的代码实现了 append 方法用于在链表末尾添加元素,get 方法用于获取指定索引处的元素,insert 方法用于在指定索引处插入元素,remove 方法用于删除指定元素。可以根据需要进一步扩展功能。
阅读全文