24. 两两交换链表中的节点
使用递归

使用的这个递归又把我弄糊涂了,只能是暂时理解这4个,如果把他想成一个整体的话,有head、next,还有一个后续的结点,前面还是有一个
class Solution {
public ListNode swapPairs(ListNode head) {
if(head == null || head.next == null) return head;
ListNode next = head.next;
head.next = swapPairs(next.next);
next.next = head;
return next;
}
}
使用迭代
创建一个哑结点

class Solution {
public ListNode swapPairs(ListNode head) {
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode temp = dummy;
while(temp.next != null && temp.next.next != null){
ListNode node1 = temp.next;
ListNode node2 = temp.next.next;
temp.next = node2;
node1.next = node2.next;
node2.next = node1;
temp = node1;
}
return dummy.next;
}
}

浙公网安备 33010602011771号