Given a linked list, swap every two adjacent nodes and return its head.
You may not modify the values in the list's nodes, only nodes itself may be changed.
给定一个链表,交换每两个相邻节点,并返回其头部节点
你不能改变链表中的值,只能改变节点本身
Example:
Given 1->2->3->4, you should return the list as 2->1->4->3.
Solutions:
Python
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
迭代的方法
"""
dummy = p = ListNode(0) #添加一个辅助头节点,dummy和p都指向这个辅助头节点
dummy.next = head #将这个辅助头节点添加到原链表前面:0->1->2->3->4
while head and head.next: #判断一对链表节点是否存在,只有在存在情况下才能交换
tmp = head.next #设置tmp指针指向节点2
head.next = tmp.next #断开1,2之间链接,将3链接在1后,变成多头链表:0->1->3->4和 2->3->4,这两个链表在2处汇合
tmp.next = head #将2,3之间的链接断开,将头节点1链接在2后面,变成多头链表:0->1->3->4 和 2->1->3->4
p.next = tmp #最后将0,1节点之间的链接断开,将2链接在0后面,至此,链表前两个元素交换完成:0->2->1->3->4
p = head #剩下的是移动p指针和head指针,来操作下一对数据,这时p应指向1,head指向3
head = head.next
return dummy.next
class Solution:
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
递归的方法
"""
def swapPairs(self, head):
if head and head.next:
tmp = head.next
head.next = self.swapPairs(tmp.next) #这一步在tmp.next为null时,将tmp的前一个节点指向了null,然后下一步交换了tmp和tmp前一个节点,思路很巧妙
tmp.next = head
return tmp
return head