两两交换链表中的节点
难度 中等
题目
给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
示例1
输入:head = [1,2,3,4]
输出:[2,1,4,3]
示例2
输入:head = []
输出:[]
示例3
输入:head = [1]
输出:[1]
解题思路:改变指针指向来交换节点
解法1:递归:此题可使用递归方法,定义指针head指向原链表的头节点(新链表的第二个节点),newhead=head.next指向原链表的第二个节点(新链表的头节点),newhead.next表示原链表的其余节点,改变指针newhead.next=head来交换前两个节点,递归head.next=swapPairs(newhead.next),来交换其余节点。递归终止条件为只剩一个节点或没有节点时为止,返回新链表的头节点newhead。
代码1
class ListNode(object):
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution(object):
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if (not head) or (not head.next):
return head
newhead = head.next
head.next = self.swapPairs(newhead.next)
newhead.next = head
return newhead
解法2:迭代:此题还可以用迭代方法,先交换链表前两个节点,迭代到交换其余节点(改变指针指向完成后移动指针,来向后迭代)。则应定义三个指针,两个指针分别指着两个节点用来交换,另一个指针应在它们之前用来串它们。先定义一个虚伪节点r=ListNode(),定义一个指针t指向它,r.next=head(先连到链表上),node1=t.next,node2=t.next.next,下面交换节点,t.next=node2,node1.next=node2.next,node2.next=node1,再移动指针t=node1,然后用一个循环控制,迭代交换其余节点,循环条件为t.next,t.next.next都不为空才进行交换。退出循环,则节点都交换完毕,返回r.next即为新的交换后的链表
代码2
class ListNode(object):
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution(object):
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
r = ListNode()
t = r
r.next = head
if (not head) or (not head.next):
return head
while t.next and t.next.next:
node1 = t.next
node2 = t.next.next
t.next = node2
node1.next = node2.next
node2.next = node1
t = node1
return r.next
至此,此题解答完毕