已解答
中等
相关标签
相关企业
给你一个链表,两两交换其中相邻的节点,并返回交换后链表的头节点。你必须在不修改节点内部的值的情况下完成本题(即,只能进行节点交换)。
示例 1:
输入:head = [1,2,3,4] 输出:[2,1,4,3]
示例 2:
输入:head = [] 输出:[]
示例 3:
输入:head = [1] 输出:[1]
提示:
- 链表中节点的数目在范围
[0, 100]
内 0 <= Node.val <= 100
# 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: Optional[ListNode]) -> Optional[ListNode]:
# 如果链表为空或者只有一个节点,直接返回头节点
if not head or not head.next:
return head
# 创建一个虚拟头节点,方便处理头节点的交换
dummy = ListNode(-1)
dummy.next = head
current = dummy
while current.next and current.next.next:
# 保存需要交换的两个节点
first = current.next
second = current.next.next
# 交换两个节点
first.next = second.next
current.next = second
second.next = first
# 移动到下一对需要交换的节点
current = first
return dummy.next
ListNode
类定义了链表的节点,包含一个值val
和一个指向下一个节点的指针next
。Solution
类中的swapPairs
方法用于交换链表中相邻的节点。算法逻辑:
- 检查特殊情况:如果链表为空或者只有一个节点,直接返回头节点。
- 创建虚拟头节点:为了避免在交换头节点时的特殊情况处理,创建一个虚拟头节点
dummy
,其next
指向实际的头节点。- 遍历链表:使用一个指针
current
从虚拟头节点开始遍历链表,每次找到两个相邻的节点,然后交换它们的位置。- 交换节点:通过改变节点的
next
指针来实现节点的交换,而不是修改节点内部的值。- 移动到下一对节点:交换完成后,移动
current
指针到下一对需要交换的节点。- 返回结果:最后返回虚拟头节点的下一个节点,即交换后的链表头节点。
这个实现满足了题目的要求,可以在不修改节点内部值的情况下完成链表中相邻节点的交换。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode swapPairs(ListNode head) {
if(head == null || head.next == null)return head;
ListNode t1 = head.next;
ListNode t2 = head.next.next;
t1.next = head;
head.next = swapPairs(t2);
return t1;
}
}
# 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: Optional[ListNode]) -> Optional[ListNode]:
# 如果链表为空或者只有一个节点,直接返回头节点
if not head or not head.next:
return head
# 创建一个虚拟头节点,方便处理头节点的交换
dummy = ListNode(-1)
dummy.next = head
current = dummy
while current.next and current.next.next:
# 保存需要交换的两个节点
first = current.next
second = current.next.next
# 交换两个节点
first.next = second.next
current.next = second
second.next = first
# 移动到下一对需要交换的节点
current = first
return dummy.next