题目链接:swap-nodes-in-pairs
/**
*
* 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.
*
*/
public class SwapNodesInPairs {
public class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}
//递归版
// 55 / 55 test cases passed.
// Status: Accepted
// Runtime: 226 ms
// Submitted: 1 minute ago
public ListNode swapPairs(ListNode head) {
if (head == null || head.next == null) return head;
ListNode node = head.next;
if(node.next == null)
head.next = null;
else
head.next = swapPairs(node.next);
node.next = head;
return node;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}