24. 两两交换链表中的节点
原始题目链接:https://leetcode-cn.com/problems/swap-nodes-in-pairs/
给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
解题思路:
解链表的题最好是画图,链表的递归解法不好想出来,通过指针迭代遍历是比较好解题的,递归的思想参考了一个题解,具体实现看代码及注释。
代码实现:
迭代遍历
# 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:
dummy = ListNode(-1)
dummy.next = head
cur_node = dummy
flag = True
while cur_node.next is not None and cur_node.next.next is not None:
start = cur_node.next
end = cur_node.next.next
# 注意cur_node需要指向翻转后的节点,因为cur_node现在指向的start节点,否则就断掉了
cur_node.next = end
start.next = end.next
end.next = start
cur_node = start
return dummy.next
递归解法
# 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 head is None or head.next is None:
return head
# 记录相邻节点的第二个节点
next_node = head.next
# 第一个节点的next域指向next_node的下一个节点
head.next = self.swapPairs(next_node.next)
# head的下一个节点next_node的next域往回指向head节点
next_node.next = head
# 返回翻转后的节点
return next_node
参考文献:
https://leetcode-cn.com/problems/swap-nodes-in-pairs/solution/hua-jie-suan-fa-24-liang-liang-jiao-huan-lian-biao/