【Hot100】LeetCode—24. 两两交换链表中的节点



1- 思路

四指针

  • 定义 dummyHead:便于处理头结点
  • cur 指针,记录两个交换节点的前 前一个结点
  • ② 第一个指针 first
  • ③ 第二个指针 second

更新:

  • 初始化 firstsecondfirst = cur.nextsecond = cur.next.next
  • 更新:结点翻转后跟新,涉及三个步骤

image.png

  • firstnext 更新 ——> ①
  • secondnext 更新 ——> ②
  • 交换后前一个结点的 next 更新 ——> ③

2- 实现

⭐24. 两两交换链表中的节点——题解思路

在这里插入图片描述

class Solution {
    public ListNode swapPairs(ListNode head) {
        ListNode dummyHead = new ListNode(-1);
        dummyHead.next = head;
        ListNode cur = dummyHead;
        ListNode first = null;
        ListNode second = null;
        while(cur.next!=null && cur.next.next != null){
            first = cur.next;
            second = cur.next.next;

            first.next = second.next;
            second.next = first;
            cur.next = second;

            cur = first;
        }
        return dummyHead.next;
    }
}

3- ACM 实现

public class swapPairs {

    public static class ListNode {
        int val;
        ListNode next;
        ListNode(int x) {
            val = x;
            next = null;
        }
    }

    public static ListNode swapPairs(ListNode head){
        // 1. 数据结构
        ListNode dummyHead = new ListNode(-1);
        dummyHead.next = head;
        ListNode cur = dummyHead;
        ListNode first = null;
        ListNode second = null;

        // 2.循环
        while(cur.next!=null && cur.next.next!=null){
            first = cur.next;
            second = cur.next.next;

            //交换
            first.next = second.next;
            second.next = first;
            cur.next = second;

            cur = first;
        }
        return dummyHead.next;
    }


    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n1 = sc.nextInt();
        ListNode head1 = null, tail1 = null;
        for (int i = 0; i < n1; i++) {
            int val = sc.nextInt();
            ListNode newNode = new ListNode(val);
            if (head1 == null) {
                head1 = newNode;
                tail1 = newNode;
            } else {
                tail1.next = newNode;
                tail1 = newNode;
            }
        }
        ListNode forRes = swapPairs(head1);
        while(forRes!=null){
            System.out.print(forRes.val+" ");
            forRes = forRes.next;
        }

    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值