给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
image.png
解题思路:
- 递归,链表长度至少大于等于2才需要交换,另tmp指向head.next即第二个节点,交换head和tmp的节点,另tmp.next指向head,head指向tmp.next,其中tmp.next为后续交换好的节点,即swapPairs(tmp.next)。
- 迭代,先令dump.next指向head,tmp指向dump,令node1、node2分别指向head和head.next,只需交换tmp的后两位,即交换node1和node2,然后tmp后移两位,继续上一步。
Python3代码:
# 递归
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
if not head or not head.next:
return head
tmp = head.next
head.next = self.swapPairs(tmp.next)
tmp.next = head
return tmp
#迭代
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
if not head or not head.next:
return head
dump = ListNode(0)
dump.next = head
tmp = dump
while tmp.next and tmp.next.next:
node1 = tmp.next
node2 = tmp.next.next
tmp.next = node2
node1.next = node2.next
node2.next = node1
tmp = tmp.next.next
return dump.next
网友评论