题目:给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
解析:
①用递归的做法,先交换当前两个结点;
②将交换后的尾结点指向下个要交换的结点;
③重复上述步骤①②,直到后面只有一个节点或没有结点。
public ListNode swapPairs(ListNode head) {
if (head == null) return null;
if (head.next == null) return head;
return swap(head);
}
public ListNode swap(ListNode node){
if (node == null) return null;
if (node.next == null) return node;//递归结束条件,当只剩下一个节点或没有结点不再交换
ListNode pNode = node.next;//当前结点的下一个节点(当前结点1的下一结点为2)
ListNode tmp = pNode.next;//保存下一个节点的指向(保存节点2的指向结点3)
pNode.next = node;//下一个节点指向当前的结点(2->1)
node.next = swap(tmp);//2->1->swap(tmp)递归下去,交换完成
return pNode;
}```