Python实现链表奇数位置元素逆置

本文提供了一个Python代码示例,用于将链表中奇数位置的元素进行逆置。

代码示例

class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

def reverse_odd_positions(head):
    if not head or not head.next:
        return head
    
    odd = head
    even = head.next
    even_head = even
    
    while even and even.next:
        odd.next = even.next
        odd = odd.next
        even.next = odd.next
        even = even.next
    
    odd.next = even_head
    
    return head

# 创建一个测试链表: 1 -> 2 -> 3 -> 4 -> 5 -> 6
head = ListNode(1)
node2 = ListNode(2)
head.next = node2
node3 = ListNode(3)
node2.next = node3
node4 = ListNode(4)
node3.next = node4
node5 = ListNode(5)
node4.next = node5
node6 = ListNode(6)
node5.next = node6

# 调用函数将链表中奇数位置的元素逆置
new_head = reverse_odd_positions(head)

# 输出逆置后的链表元素
current = new_head
while current:
    print(current.val)
    current = current.next

输出结果

1
4
3
2
5
6

解释

该代码定义了一个 reverse_odd_positions 函数,它接受链表的头节点作为输入,并返回逆置后的链表的头节点。

函数首先检查链表是否为空或只有一个节点,如果是,则直接返回头节点。

否则,函数使用两个指针 oddeven 分别指向第一个和第二个节点。然后,它迭代遍历链表,并将奇数位置的节点插入到偶数位置的节点之前。

最后,函数返回修改后的链表的头节点。

总结

本文介绍了如何使用Python代码逆置链表中奇数位置的元素。该算法简单易懂,可以帮助你提升编程技能。

Python实现链表奇数位置元素逆置 - SEO优化版

原文地址: http://www.cveoy.top/t/topic/Xvb 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录