python链表——链表相连3个节点翻转

本文介绍了一种链表中每三个节点进行反转的算法实现,通过详细的Python代码展示了如何仅用一次遍历即可完成每三个一组的节点反转,并保持其余节点顺序不变。此方法适用于需要对链表进行特定模式变换的场景。

输入:1->2->3->4->5->6->7->8

输出:3->2->1->6->5->4->7->8

 

代码

def reverse_3(head):
    if head is None or head.next is None or head.next.next is None:
        return head
    cur1 = head
    cur2 = head.next
    cur3 = head.next.next
    head = cur3
    while cur3.next and cur3.next.next and cur3.next.next.next:
        # 赋值的指针操作
        nex1 = cur3.next
        nex2 = cur3.next.next
        nex3 = cur3.next.next.next
        # 3个节点内,指针转向
        cur3.next = cur2
        cur2.next = cur1
        cur1.next = nex3
        # 移动三个操作变量,到下一轮的3个节点
        cur1 = nex1
        cur2 = nex2
        cur3 = nex3
    # 循环结束时,将未完成的指针方向,补充上去
    nex1 = cur3.next
    cur3.next = cur2
    cur2.next = cur1
    cur1.next = nex1
    return head
# 测试
link = LinkedList()
print("=========before============")
link.add(1)
link.add(2)
link.add(3)
link.add(4)
link.add(5)
link.add(6)
link.add(7)
link.add(8)
link.print_link()
print("=========after============")
new_head = reverse_3(link.head)

while new_head:
    print(new_head.data)
    new_head = new_head.next
# 结果
=========before============
1
2
3
4
5
6
7
8
=========after============
3
2
1
6
5
4
7
8

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值