noaman_wgs

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
//给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。 
//
// 你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
//
//
//
// 示例 1:
//
//
//输入:head = [1,2,3,4]
//输出:[2,1,4,3]
//
//
// 示例 2:
//
//
//输入:head = []
//输出:[]
//
//
// 示例 3:
//
//
//输入:head = [1]
//输出:[1]
//
//
//
//
// 提示:
//
//
// 链表中节点的数目在范围 [0, 100] 内
// 0 <= Node.val <= 100
//
//
//
//
// 进阶:你能在不修改链表节点值的情况下解决这个问题吗?(也就是说,仅修改节点本身。)
// Related Topics 递归 链表
// 👍 834 👎 0



class Solution {
    public ListNode swapPairs(ListNode head) {
        if (head == null) {
            return null;
        }

        List<ListNode> list = new ArrayList<>();
        while (head != null) {
            list.add(head);
            head = head.next;
        }
        if (list.size() == 1) {
            return list.get(0);
        }

        ListNode pNode = new ListNode(-1);
        ListNode swap = pNode;
        int step = 1;
        while (step < list.size()) {
            pNode.next = list.get(step);
            pNode = pNode.next;
            pNode.next = list.get(step - 1);
            pNode = pNode.next;

            // 奇数时,到达倒数第2个时,剩下的直接返回即可
            if (step + 1 == list.size() - 1) {
                pNode.next = list.get(step + 1);
                pNode = pNode.next;
                break;
            } else {
                step += 2;
            }
        }

        // 很重要的一步,否则会出现链表循环
        pNode.next = null;

        return swap.next;

    }
}

 

posted on 2021-03-03 00:14  noaman_wgs  阅读(47)  评论(0编辑  收藏  举报