成对交换链表节点

题目:

对于一组给定链表,交换相邻结点。并返回头结点

示例:

例如: 1->2->3->4
返回: 2->1->4->3.

可以用3个指针:用head指向需要交换结点的前一个结点;用n1指向需要交换的第一个结点;n2指向需要交换的第二个结点。

然后不断交换n1、n2的位置即可。

class LNode:
    def __init__(self, elem):
        self.elem = elem
        self.next = None


def swapPairs(head):
    if head is None or head.next is None:  # 如果输入的链表是空或者只有一个结点,直接返回当前结点
        return head
    new = LNode(0) #新建一个表头,其中的元素为0
    new.next = head
    head = new

    while head.next is not None and head.next.next is not None:
        n1 = head.next
        n2 = head.next.next
        # 交换n1、n2的指向
        head.next = n2
        n1.next = n2.next
        n2.next = n1
        # 将head指向此时的n1
        head = n1
    return new.next


if __name__ == "__main__":
    head = LNode(1)
    p1 = LNode(2)
    p2 = LNode(3)
    p3 = LNode(4)
    head.next = p1
    p1.next = p2
    p2.next = p3
    p = swapPairs(head)
    while p:
        print(p.elem)
        p = p.next

参考:https://www.cnblogs.com/bozhou/p/6956178.html

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值