24. 两两交换链表中的节点!

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

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

示例:

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

中等
【分析】暴力遍历,直观易懂。举个栗子,给定1→2→3→4:
先设定一个哑节点0: 0→1→2→3→4
在这里插入图片描述
交换:

cur.next=next.next
pre.next=next
next.next=cur

在这里插入图片描述
确定下一步的pre,cur,next:

pre=cur
cur=cur.next
next=cur.next

在这里插入图片描述
确定遍历的停止条件(当最后链表只有一个元素或者没有元素时即停止):
cur==None:(当没有元素可以交换时:)
在这里插入图片描述

cur.next==None:(当只有一个元素时:)

在这里插入图片描述

所以,这里把cur==None作为跳出循环的条件,另外,next=cur.next放在循环开始时进行。if cur.next==None: break 即可

# 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
        """
        dummy=ListNode(0)
        pre=dummy
        pre.next=head
        while head and head.next:
            Next=head.next
            
            head.next=Next.next
            pre.next=Next
            Next.next=head
             
            pre=head
            head=head.next
        return dummy.next       

注意(易错):前面的dummy设置很重要,因为如果不设dummy的话,后面pre,head(cur)都会变化,到时候就返回不了正确答案了。

【分析】递归法:
head→next→head'→next'→…经过一轮交换之后变成如下形式:
next→head→head'→next'→

fun swap(head):
    next=head.next
    head.next=swap(next.next即下一轮交换的head) 
    next.next=head
    return next

返回next,因为一轮交换之后这一轮的next变成了当前链表的头节点。
注意递归的出口head==None or head.next==None,注意此时返回的应该时这个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
        """
        if head==None or head.next==None:
            return head
        Next=head.next
        head.next=self.swapPairs(Next.next)
        Next.next=head
        
        return Next
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值