leetcode24. Swap Nodes in Pairs【Python刷题】链表交换相邻位置

44 篇文章 1 订阅
33 篇文章 0 订阅

Given a linked list, swap every two adjacent nodes and return its head.

Example:

Given 1->2->3->4, you should return the list as 2->1->4->3.

Note:

  • Your algorithm should use only constant extra space.
  • You may not modify the values in the list's nodes, only nodes itself may be changed.

有一种代码叫做别人的代码

而且最开始还看错了 以为是反转链表MDZZ

先看我丑陋的代码

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def swapPairs(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if head==None or head.next==None:
            return head
        p=ListNode(0)
        p.next=head
        l1=ListNode(0)
        l1=head
        l2=ListNode(0)
        l2=l1.next
        
        l1.next=l2.next
        l2.next=l1
        head=l2
        p.next=l2
        while(1):
            l1=l1.next
            if  l1==None:
                break
            l2=l1.next
            if l2==None:
                break
            p=p.next
            p=p.next
            l1.next=l2.next
            l2.next=l1
            p.next=l2
        return head

再看看人家的

话说 等号运算符是从右向左进行运算的呢

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def swapPairs(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        pre,pre.next=self,head
        while pre.next!=None and pre.next.next!=None:
            a=pre.next
            b=a.next
            pre.next,b.next,a.next=b,a,b.next
            pre=a
        return self.next
        

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值