1. 程式人生 > >leetcode-24. Swap Nodes in Pairs

leetcode-24. Swap Nodes in Pairs

題目型別:連結串列

題意:

給出一個連結串列,按對交換節點,
- 常數空間
- 不能用改變節點的值的方法做,需要交換節點本身。

我的思路:迭代。兩兩交換,修改next等指標

效率:10%

對於當前節點first,和下一個節點second
- 記錄上一次交換後的最後一個節點pre
- 因為交換後連結串列斷裂,所以暫存second下一個節點的位置,temp = second.next;
- pre.next = second; second.next = first; first.next = temp;
- 更新pre = first,繼續交換下面的節點

class Solution {
    public ListNode swapPairs(ListNode head) {
        if (head == null || head.next == null) return head;
        ListNode pre = new ListNode(0);
        ListNode copy = pre;
        ListNode first = head;
        ListNode second = head.next;
        while (first != null && second != null) {
            first.next
= second.next;//相當於 暫存下一個的指標 pre.next = second; second.next = first; pre = first; first = first.next; second = (first != null) ? first.next : null; } return copy.next; } }

方法二:遞迴

效率略高於迭代

    //方法二:遞迴
    public
ListNode swapPairs(ListNode head) { if (head == null || head.next == null) return head; ListNode temp = head.next;// 最終結果的頭指標必定是第二個節點 head.next = swapPairs(head.next.next); temp.next = head; return temp; }