在链表中通过序号查找节点,通常意味着链表是有序的,因为链表通常通过指针来连接节点,而不是通过索引。以下是一个简单的示例,演示了如何在有序链表中通过序号查找节点。
定义链表节点的结构:
```python
class ListNode:
def __init__(self, value=0, next=None):
self.value = value
self.next = next
```
然后,实现一个函数来查找指定序号的节点:
```python
def find_node_by_index(head, index):
current = head
current_index = 0
while current is not None:
if current_index == index:
return current
current = current.next
current_index += 1
return None 如果索引超出范围,返回None
```
使用这个函数的例子:
```python
创建一个链表:1 -> 2 -> 3 -> 4 -> 5
head = ListNode(1, ListNode(2, ListNode(3, ListNode(4, ListNode(5)))))
查找索引为2的节点(值为3)
node = find_node_by_index(head, 2)
if node:
print(f"Node value at index 2: {node.value