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.
Example:
Given 1->2->3->4, you should return the list as 2->1->4->3.
按顺序将给定的链表中的元素两两交换,但不能更改结点中的值,只能对结点本身进行操作。
问题中包含链表和子结点等概念,且结点需要变动,很容易想到利用递归来解决,直接上代码。
或者直接将结点拆下放到新链表中更简单。
class Solution {
    public ListNode swapPairs(ListNode head) {
        // 递归边界,当待交换结点数不足2时直接返回
        if (head == null || head.next == null) {
            return head;
        }
        ListNode first = head;
        ListNode second = first.next;
        first.next = swapPairs(second.next);
        second.next = first;
        return second;
    }
}
/**
 * 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}
 */
var swapPairs = function (head) {
  let dummy = new ListNode()
  let cur = dummy
  while (head !== null) {
    let a = head, b = head.next
    if (b !== null) {
      head = b.next
      b.next = a
      a.next = null
      cur.next = b
      cur = a
    } else {
      cur.next = a
      head = null
    }
  }
  return dummy.next
}
/**
 * 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}
 */
var swapPairs = function (head) {
  if (head === null) {
    return null
  }
  if (head.next !== null) {
    let nextHead = swapPairs(head.next.next)
    head.next.next = head
    head = head.next
    head.next.next = nextHead
  }
  return head
}
原文:https://www.cnblogs.com/mapoos/p/13175022.html