[List-medium] 24. Swap Nodes in Pairs switching elements in the list of the positions of two adjacent

1. The title site

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

2. Title Description

Here Insert Picture Description

3. subject to the effect

Given a list, the list of adjacent switching position of two elements. That element must swap adjacent position

4. Problem-solving ideas

  • Define a header ListNode node as the primary node, and then connected to the head by a given node list.
  • Redefinition ListNode two nodes, the list is used as a temporary variable two adjacent nodes exchange.

5. AC Code

class Solution {
    public ListNode swapPairs(ListNode head) {
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode cur = dummy;
        ListNode l1 = null;
        ListNode l2 = null;
        while(cur.next != null && cur.next.next != null) {
            l1 = cur.next;
            l2 = cur.next.next;
            l1.next = l2.next;
            l2.next = l1;
            cur.next = l2;
            cur = l1;
        }
        return dummy.next;
    }
}

Guess you like

Origin blog.csdn.net/xiaojie_570/article/details/93398970