思路:
// @Title: 两两交换链表中的节点 (Swap Nodes in Pairs)
// @Author: qisiii
// @Date: 2024-09-12 00:41:34
// @Runtime: 0 ms
// @Memory: 40.3 MB
// @comment:
// @flag:
/**
* 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 next = head.next;
head.next = swapPairs(next != null ? next.next : null);
if (next != null) {
next.next = head;
}
return next;
}
}
思路:官方题解
// @Title: 两两交换链表中的节点 (Swap Nodes in Pairs)
// @Author: qisiii
// @Date: 2024-04-13 21:13:33
// @Runtime: 0 ms
// @Memory: 40.2 MB
// @comment: 官方题解
// @flag: WHITE
/**
* 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 temp = head.next;
head.next=swapPairs(head.next.next);
temp.next=head;
return temp;
}
}
+++ title = “两两交换链表中的节点 (Swap Nodes in Pairs)” draft = false +++
思路:借用临时的头
// @Title: 两两交换链表中的节点 (Swap Nodes in Pairs)
// @Author: qisiii
// @Date: 2024-04-13 21:09:02
// @Runtime: 0 ms
// @Memory: 40.5 MB
// @comment: 借用临时的头
// @flag: WHITE
/**
* 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;
}
//-1->2
ListNode temp = new ListNode(-1, head.next);
//临时存储3
ListNode next = head.next.next;
//断开2和3
head.next.next = null;
//断开1和2
head.next=null;
temp.next.next = head;
head.next = swapPairs(next);
return temp.next;
}
}