数据结构编程实现单向链表的操作获取某个元素的下一个元素
时间: 2023-05-26 20:03:22 浏览: 93
数据结构 单链表的操作实现
以下是Python实现:
```python
class Node:
def __init__(self, data=None):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def append(self, data):
node = Node(data)
if not self.head:
self.head = node
else:
current = self.head
while current.next:
current = current.next
current.next = node
def get_next(self, data):
current = self.head
while current and current.data != data:
current = current.next
if current:
return current.next
return None
```
使用示例:
```python
linked_list = LinkedList()
linked_list.append(1)
linked_list.append(2)
linked_list.append(3)
next_element = linked_list.get_next(2)
if next_element:
print(next_element.data) # 输出 3
else:
print("2 在链表中不存在")
```
阅读全文