24. 两两交换链表中的节点 方法一:迭代,虚拟头结点
class Solution {
public ListNode swapPairs(ListNode head) {
ListNode dummyNode = new ListNode(0);
dummyNode.next = head;
ListNode prev = dummyNode;
while(prev.next != null && prev.next.next != null){
ListNode temp = head.next.next;
prev.next = head.next;
head.next.next = head;
head.next = temp;
prev = head;
head = head.next;
}
return dummyNode.next;
}
}
方法二:1.递归
class Solution {
public ListNode swapPairs(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode one = head;
ListNode two = one.next;
ListNode three = two.next;
two.next = one;
one.next = swapPairs(three);
return two;
}
}
方法二:2.递归
class Solution {
public ListNode swapPairs(ListNode head) {
if(head == null || head.next == null){return head;}
ListNode next = head.next;
ListNode newNode = swapPairs(next.next);
next.next = head;
head.next = newNode;
return next;
}
}
|