# 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 c
# hanged.
#
#
# Example 1:
#
#
# Input: head = [1,2,3,4]
# Output: [2,1,4,3]
#
#
# Example 2:
#
#
# Input: head = []
# Output: []
#
#
# Example 3:
#
#
# Input: head = [1]
# Output: [1]
#
#
#
# Constraints:
#
#
# The number of nodes in the list is in the range [0, 100].
# 0 <= Node.val <= 100
#
# Related Topics 链表
# 👍 680 👎 0
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
# leetcode submit region begin(Prohibit modification and deletion)
# 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: return None
if not head.next: return head
pre = head
post = pre.next
head = post
# 虚节点
lastTail = ListNode(0)
lastTail.next = pre
while True:
pre.next = post.next
post.next = pre
lastTail.next = post
lastTail = pre
pre = pre.next
if not pre: break
post = pre.next
if not post: break
return head
# leetcode submit region end(Prohibit modification and deletion)
迭代解法,写的还是麻烦了点,官方题解有递归算法值得学习:
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
if not head or not head.next:
return head
newHead = head.next
head.next = self.swapPairs(newHead.next)
newHead.next = head
return newHead
该博客讨论了一个链表问题,即如何交换链表中每两个相邻节点。提供了两种解决方案,一种是迭代方法,虽然相对复杂,但能完成任务;另一种是递归算法,更为简洁。所有代码都以Python实现,并附带了示例输入和输出,以及题目约束。
526

被折叠的 条评论
为什么被折叠?



