两两交换链表中的节点

给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。

 

 

 

常规方法

    public static ListNode swapPairs(ListNode head) {

        ListNode h = new ListNode(0);
        h.next = head;

        ListNode temp = h;   //指向上次交换的最后一个节点
        ListNode p = head;
        ListNode q;
        while(p != null && p.next != null) {
            // 交换p、q两个节点
            q = p.next;
            p.next = q.next;
            q.next = p;

            // temp.next指向交换后的第一个节点
            // 同时指向交换后的最后一个节点
            temp.next = q;
            temp = p;

            p = p.next;
        }
        return h.next;
    }

 

递归方法:

    public static ListNode test(ListNode head) {

        if (head==null || head.next == null) return head;

        ListNode temp = head.next;
        head.next = temp.next;
        temp.next = head;

        head.next = test(head.next);
        return temp;
    }

 

posted on 2018-04-26 20:42  Deltadeblog  阅读(141)  评论(0编辑  收藏  举报

导航