題目鏈接:?https://leetcode.com/problems/swap-nodes-in-pairs/?tab=Description
Problem: 交換相鄰的兩個節點

如上圖所示,遞歸進行交換。從最尾端開始,當最尾端只有一個節點時,停止交換
否則執行 swap(head.next)?
參考代碼:
package leetcode_50;/*** * @author pengfei_zheng* 交換相鄰節點*/ public class Solution24 {public class ListNode {int val;ListNode next;ListNode(int x) { val = x; }}public ListNode swapPairs(ListNode head) {if ((head == null)||(head.next == null))return head;ListNode n = head.next;head.next = swapPairs(head.next.next);n.next = head;return n;} }
?