[Leetcode]24. 两两交换链表中的节点

题目描述

给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。

你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

示例:

给定 1->2->3->4, 你应该返回 2->1->4->3.

我的方法:

看起来并不算很难,重点应该在于理顺整个处理流程。

  1. 将节点分为两两一组,每次处理两个节点。
  2. 对于头两个节点,交换两个节点后,只需要考虑整体的之后节点即可。
  3. 对于中间的节点,交换两个节点后,要考虑整体之前的节点以及整体之后的节点。
  4. 如果最终有节点落单,则不进行交换操作。

战绩一般:执行用时 : 32 ms, 在Swap Nodes in Pairs的Python提交中击败了9.28% 的用户。内存消耗 : 11.6 MB, 在Swap Nodes in Pairs的Python提交中击败了0.00% 的用户。

# 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 is None or head.next is None:
            return head
        # 如果长度在2以上
        p=head.next
        pre=None
        # 遍历链表
        while head:
            # 两两节点为一组,进行处理
            a=head
            b=a.next
            if b:
                head=b.next #链表要持续移动
                #交换两个节点
                if pre:
                    pre.next=b
                    b.next=a
                else:
                    b.next=a
                a.next=None #不要形成环链
                pre=a
            else:
                head=b#链表要持续移动
                if pre:
                    pre.next=a
        return p

别人的方法:

看了下别人的方法,确实很简洁。看起来是用的递归,没错,这个问题用递归解决很适合。

class Solution(object):
    def swapPairs(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if not head or not head.next:
            return head
        
        chead = self.swapPairs(head.next.next)
        hnext = head.next
        head.next, hnext.next = chead, head
        return hnext
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值