24. 两两交换链表中的节点

174 阅读1分钟

方法一:迭代

class Solution {
    public ListNode swapPairs(ListNode head) {
        ListNode dummy = new ListNode();
        dummy.next = head;
        ListNode pre = dummy, cur = head;
        while (cur != null && cur.next != null) {//边界条件,画个图
            //两个一组翻转,m到n翻转的标准程序
            ListNode tmp = cur.next;
            cur.next = tmp.next;
            tmp.next = cur;
            pre.next = tmp;
            //翻转完了,指针往后挪
            pre = cur;
            cur = pre.next;
        }
        return dummy.next;
    }
}

方法二:递归

//递归,optimized
class Solution {
    public ListNode swapPairs(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode tmp = head.next;
        head.next = swapPairs(tmp.next);
        tmp.next = head;
        return tmp;
        
    }
}

//递归,指针改方向时 顺序不好
class Solution {
    public ListNode swapPairs(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode tmp = head.next.next;
        ListNode res = head.next;
        head.next.next = head;
        head.next = swapPairs(tmp);
        return res;
    }
}