题解 | #两两交换链表的节点#
两两交换链表的节点
https://www.nowcoder.com/practice/71f95c23810349f782a1aa6c9bd714b4
import java.util.*;
/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 *   public ListNode(int val) {
 *     this.val = val;
 *   }
 * }
 */
public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param head ListNode类
     * @return ListNode类
     */
    public ListNode swapLinkedPair (ListNode head) {
        // write code here
        // 解题思路:还记得每k哥反转么? 两两交互也就是k=2
        return swapTwo(head);
    }
    public ListNode swapTwo (ListNode head) {
        // write code here
        ListNode tailNext = head;
        for (int i = 0; i < 2; i++) {
            if (tailNext == null) {
                return head;
            }
            tailNext = tailNext.next;
        }
        ListNode cur = head;
        ListNode next = null;
        ListNode pre = null;
        while (cur != tailNext) {
            next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }
        head.next = swapTwo(tailNext);
        return pre;
    }
}
查看15道真题和解析