class Solution {
public ListNode swapPairs(ListNode head) {
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode current = dummy;
// 遍历链表并交换节点
while (current.next != null && current.next.next != null) {
ListNode first = current.next;
ListNode second = current.next.next;
// 交换这两个节点
first.next = second.next;
current.next = second;
current.next.next = first;
// 移动到下一个节点
current = current.next.next;
}
return dummy.next;
}
}
24两两交换链表中的节点
最新推荐文章于 2024-10-09 22:28:58 发布