題意:給定一個鏈表,要求兩兩交換鏈表中相鄰的兩節點,比如1->2->3->4變爲2->1->4->3
思路:最簡便的方法就是遞歸,頭結點的下一個節點是已經轉換好的節點的頭結點,之後再把原來頭結點的下一節點接到頭結點上即可
class Solution {
public ListNode swapPairs(ListNode head) {
if (head == null || head.next == null)
return head;
ListNode next = head.next;
head.next = swapPairs(next.next);
next.next = head;
return next;
}
}