leetcode-24,交換連結串列相鄰節點,遞迴實現
阿新 • • 發佈:2019-01-28
給定一個連結串列,對每兩個相鄰的結點作交換並返回頭節點。
例如:
給定 1->2->3->4
,你應該返回 2->1->4->3
。
你的演算法應該只使用額外的常數空間。不要修改列表中的值,只有節點本身可以更改。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode swapPairs(ListNode head) {
if (head==null||head.next==null) {
return head;
}
ListNode temp = head.next;
head.next = temp.next;
temp.next = head;
head.next = swapPairs(head.next);
return temp;
}
}