把偶数序号的元素调至链表的前部,并写出指针代码
时间: 2024-10-16 11:15:14 浏览: 11
要实现这个功能,我们可以遍历链表,每次遇到偶数序号的节点时,将其与当前头节点交换位置。这里有一个简单的Python示例来说明这个过程[^1]:
```python
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def move_even_to_front(head):
if not head or not head.next:
return head
even_head = None
odd_head = head
prev = None
while odd_head:
if odd_head.val % 2 == 0:
if not even_head:
even_head = odd_head
else:
even_head.next = odd_head
even_head = even_head.next
else:
if not prev:
odd_head.next = even_head
else:
prev.next = odd_head.next
prev = odd_head
odd_head = odd_head.next
if odd_head and not even_head:
even_head.next = odd_head
return even_head
# 示例链表
# 1 -> 2 -> 3 -> 4 -> 5 -> 6
head = ListNode(1)
head.next = ListNode(2)
head.next.next = ListNode(3)
head.next.next.next = ListNode(4)
head.next.next.next.next = ListNode(5)
head.next.next.next.next.next = ListNode(6)
new_head = move_even_to_front(head)
while new_head:
print(new_head.val, end=" -> ")
new_head = new_head.next
# 输出: 2 -> 4 -> 6 -> 1 -> 3 -> 5 ->
```
在这个代码中,我们首先定义了一个`ListNode`类表示链表节点。`move_even_to_front`函数接受链表头节点作为参数,通过迭代操作,将偶数序号的节点移到前面。
阅读全文