简介

设置多个指针.

code

class Solution {
    public ListNode swapPairs(ListNode head) {
        if(head == null) return null;
        ListNode newHead = new ListNode(-1, null);
        newHead.next = head;
        ListNode newTail = new ListNode(-1, null);
        ListNode p1 = newHead;
        ListNode p2 = head;
        ListNode p3 = head.next;
        ListNode p4 = null;
        while(p3 != null){
            p4 = p3.next;
            p1.next = p3;
            p2.next = p4;
            p3.next = p2;
            if(p4 == null) return newHead.next;
            p4 = p2;
            p2 = p3;
            p3 = p4;
            p1 = p1.next.next;
            p2 = p2.next.next;
            p3 = p3.next.next;
        }
        return newHead.next;
    }
}

但是我觉得递归更合适

code

class Solution {
    public ListNode swapPairs(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode newHead = head.next;
        head.next = swapPairs(newHead.next);
        newHead.next = head;
        return newHead;
    }
}
posted on 2021-06-04 11:10  HDU李少帅  阅读(30)  评论(0编辑  收藏  举报