題目:給定一個鏈表,兩兩交換其中相鄰的節點,並返回交換後的鏈表。
解析:
①用遞歸的做法,先交換當前兩個結點;
②將交換後的尾結點指向下個要交換的結點;
③重複上述步驟①②,直到後面只有一個節點或沒有結點。
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;
}```