其他分享
首页 > 其他分享> > 再战leetcode(两两交换链表中的节点)

再战leetcode(两两交换链表中的节点)

作者:互联网

24. 两两交换链表中的节点

题目描述

在这里插入图片描述

想法

在这里插入图片描述

代码

class Solution {
    public ListNode createListNode(int n) {
        ListNode head = null, tmp = null, tail = null;
        int data;
        Scanner scanner = new Scanner(System.in);
        System.out.println("开始创建链表");
        for (int i = 0; i < n; i++) {
            data = scanner.nextInt();
            tail = new ListNode(data, null);
            if (head == null) {
                head = tail;
            } else {
                tmp.next = tail;
            }
            tmp = tail;
        }
        return head;
    }

    public ListNode swapPairs(ListNode head) {
        ListNode resultHead = new ListNode();
        resultHead.next = head;
        ListNode curNode = resultHead;
        while (curNode != null && curNode.next != null && curNode.next.next != null) {
            ListNode first = curNode;
            ListNode second = first.next;
            ListNode third = second.next;

            // 进行交换
            first.next = third;
            second.next = third.next;
            third.next = second;

            // 标杆为向前进2位
            curNode = curNode.next.next;
        }
        return resultHead.next;
    }
}

参考

leetcode题解

标签:head,ListNode,next,链表,tail,再战,curNode,null,leetcode
来源: https://blog.csdn.net/Leiyi_Ann/article/details/122399658