preface

So my first thought here is K flipped lists, K is 2. And on second thought, no need. If the above method is really simple problems complicated. Just three Pointers (to swapped, to swap, to swap) + iteration.

1. Title Description

Description of leetCode:

  • A linked list in which adjacent nodes are swapped in pairs and the head of the swapped list is returned. You must do this without changing the values inside the nodes (that is, swapping nodes only).
  • Example:

Second, the problem solving

2.1 train of thought

  • An empty list, a list with only one node, does not need swapping
  • Virtual head node: The virtual head is required because the previous node of the head node needs to be operated on
  • Iteration, iteration continues under the condition that the number of switching nodes is greater than 2
  • How do I swap each time? Look at the code, it’s actually a head plug.Insert the deleted tail into the swapped tailThis is an exchange of emphasis.

2.2 code

Git code address

/** * Definition for singly-linked list. * function ListNode(val, next) { * this.val = (val===undefined ? 0 : val) * this.next = (next===undefined ? null : Next) *} */ /** * @param {ListNode} head * @return {ListNode} */ const swapPairs = function (head) { Only a linked list of nodes do not need to exchange the if (head = = = null | | head. The next = = = null) return the head / / virtual head node, Let dummy = new ListNode(-1, head) let dummy = new ListNode(-1, head) While (pre-.next && pre-.next-next) {// first points to the first node, second points to the second node (where nodes are to be switched in pairs) let first = pre-.next, Second = pre. Next. Next // Next = second. Next = first. Next = second. Pre = first} return dummy. Next}Copy the code