Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given 1->2->3->4
, you should return the list as 2->1->4->3
.
Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.
思路:交换链表的前两个节点 p1,p2,保存pnext = p2.next;交换后为p2,p1,p1.next = swap(pnext);即递归调用交换链表前两个节点的方法
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode swapPairs(ListNode head) {
if (head == null || head.next == null) return head;
ListNode res = new ListNode(0);
res.next = head;
ListNode p1 = res.next;
ListNode p2 = res.next.next;
ListNode pnext = res.next.next.next;
res.next = p2;
p2.next = p1;
p1.next = swapPairs(pnext);
return res.next;
}
}