字节-LeetCode【24. 两两交换链表中的节点】

时间:2021-03-03 12:23:26   收藏:0   阅读:0
//给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。 
//
// 你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
//
//
//
// 示例 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;

    }
}

 

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!