24. 两两交换链表中的节点 Swap Nodes in Pairs

Given a linked list, swap every two adjacent nodes and return its head.

You may not modify the values in the list's nodes. Only nodes itself may be changed.

Input: head = [1,2,3,4]
Output: [2,1,4,3]

 

方法一:递归

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;
        
    }

 

方法二:依次交换

public ListNode swapPairs(ListNode head) {
        if(head ==null || head.next == null)
            return head;
        ListNode dumpy = new ListNode();
        dumpy.next = head;
        ListNode pre = dumpy;
        while ( head!=null && head.next !=null){
             pre.next = head.next;
             ListNode tmp = head.next;
             head.next = head.next.next;
             tmp.next = head;
             pre = head;
             head = head.next;
        }

        return dumpy.next;

    }

参考链接:

https://leetcode.com/problems/swap-nodes-in-pairs/

https://leetcode-cn.com/problems/swap-nodes-in-pairs/

posted @ 2020-12-07 18:40  diameter  阅读(95)  评论(0编辑  收藏  举报