算法38--Swap Nodes in Pairs

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->3Note:
  • 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

给定一个单链表,依次交换每两个节点。

思路一利用三指针pre  pcur  pnext来依次操作:

每次遍历以两个节点为单位    pre---pcur--pnext

执行操作    交换两个指针

pcur.next = pnext.next

pnext.next = pcur

pre.next = pcur

依次移动指针,进行下一次循环,但是要主要空指针的验证

pre = pcur

pcur = pcur.next

pnext = pcur.next

class Solution:
    def swapPairs(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if head==None or head.next==None:
            return head
        first = head
        second = head.next
        first.next = second.next
        second.next = first
        head = second
        if first.next==None:
            return head
        pcur = first.next    
        if pcur==None or pcur.next==None:
            return head
        pnext = pcur.next
        pre = first
        while pcur!= None and pnext!=None:
            pcur.next = pnext.next
            pnext.next = pcur
            pre.next = pnext
            pre = pcur                          
            pcur = pcur.next
            if pcur!=None and pcur.next!=None:                
                pnext = pcur.next
        return head

思路二利用递归思想来实现:

head--head.next---head.next.next----

假定head.next以后节点已经交换完成且头指针为newhead

head--head.next---newhead

指针交换,完成交换

next = head.next

head.next = newhead

next.next = head

return next

递归的基准条件是head==None 或者head.next==None  此时说明没有节点可以交换,返回即可

class Solution:
    def swapPairs(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if head!=None and head.next!=None:
            newhead = self.swapPairs(head.next.next)
            next = head.next
            head.next = newhead
            next.next = head
            return next
        else:
            return head

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值