python链表相邻两个元素翻转(如head->1->2->3->4->5->6->7相邻元素翻转后head->2->1->4->3->6->5->7)

#链表相邻两个元素翻转(如head->1->2->3->4->5->6->7相邻元素翻转后head->2->1->4->3->6->5->7)
class Node:
    def __init__(self,value,next):
        self.value=value
        self.next=next
def reverse(head):
    if head==None or head.next==None:
        return 0
    cur=head.next #初始化cur为1
    pre=head #初始化cu1的pre为head
    next=None #初始化1的next为空
    while cur!=None and cur.next!=None: #分奇偶两种情况
        next=cur.next.next #1与6共同决定链表循环遍历,next=3
        pre.next=cur.next #head->2
        cur.next.next=cur #2->1,此时head->2->1
        cur.next=next #1->3,此时head->2->1->3->4->5->6,完成1与2的翻转
        pre=cur #pre=1
        cur=next #cur=3,进入新一轮翻转,此时cur=3,pre=1
    return head
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值