给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
示例:
给定 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