![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/0529483d7fee9daf1816a7661916aa87.png)
答案
1、栈
class Solution {
public ListNode swapPairs(ListNode head) {
if(head==null || head.next==null) {
return head;
}
Stack<ListNode> stack = new Stack<ListNode>();
ListNode p = new ListNode(-1);
ListNode cur = head;
head = p;
while(cur!=null && cur.next!=null) {
stack.add(cur);
stack.add(cur.next);
cur = cur.next.next;
p.next = stack.pop();
p = p.next;
p.next = stack.pop();
p = p.next;
}
if(cur!=null) {
p.next = cur;
} else {
p.next = null;
}
return head.next;
}
}
2、迭代:三个指针
class Solution {
public ListNode swapPairs(ListNode head) {
ListNode p = new ListNode(-1);
p.next = head;
ListNode a = p;
ListNode b = p;
ListNode tmp = p;
while(b!=null && b.next!=null && b.next.next!=null) {
a = a.next;
b = b.next.next;
tmp.next = b;
a.next = b.next;
b.next = a;
tmp = a;
b = a;
}
return p.next;
}
}
3、递归
class Solution {
public ListNode swapPairs(ListNode head) {
if(head==null || head.next==null) {
return head;
}
ListNode tmp = head.next;
head.next = swapPairs(tmp.next);
tmp.next = head;
return tmp;
}
}