24. 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.

 含义:两两交换相邻的节点

1     public ListNode swapPairs(ListNode head) {
2         if (head  == null || head.next == null) return head;
3         ListNode p = head.next;
4         head.next = swapPairs(p.next);
5         p.next = head;
6         return p; 
7     }

 

 

 
posted @ 2017-10-25 15:33  daniel456  阅读(108)  评论(0编辑  收藏  举报