题目描述
将给定的链表中每两个相邻的节点交换一次,返回链表的头指针
例如,
给出1->2->3->4,你应该返回链表2->1->4->3。
你给出的算法只能使用常量级的空间。你不能修改列表中的值,只能修改节点本身。示例1
输入
{1,2}输出
{2,1}
/**
* 用递归
* @param head ListNode类
* @return ListNode类
*/
public ListNode swapPairs (ListNode head) {
if(head==null || head.next == null){
return head;
}
ListNode curNode = head.next;
ListNode nextNode = head.next.next;
curNode.next = head;
head.next = swapPairs(nextNode);
return curNode;
}