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

题目

给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。

你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

思路

创建虚拟头节点,画图,确认步骤。

实现

java 复制代码
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode swapPairs(ListNode head) {
       
       if(head == null || head.next == null) return head;
      
       ListNode dummy = new ListNode(0);
       ListNode p = dummy;
       dummy.next = head;
       ListNode i = head;
       ListNode j = head.next;

       // i 是第一个节点 j是第二个节点
      
      //一轮下来 i!=null 且 j != null 就可以进行循环
       while(i !=null && j != null){
         
         ListNode temp = j.next;


         //实际的交换步骤
         p.next = j;
         j.next = i;
         i.next = temp;

          
         p = i;
         i = temp;
         //这里是为了防止下面出现NPE。
         //当移动指针准备下一轮循环的时候,发现第一个已经是null,可以直接返回退出循环了
         if(i == null){
            continue;
         }
         j = temp.next;
       }

       return dummy.next;
    }
}
相关推荐
小七在进步18 小时前
数据结构:栈与队列之栈的实现
数据结构
小小龙学IT18 小时前
C++ 并发编程深度解析:从内存模型到无锁数据结构
数据结构·c++
变量未定义~19 小时前
单调栈、单调队列(模板)、子矩阵(模板)
数据结构·算法·蓝桥杯
不会就选b20 小时前
算法日常・每日刷题--<快速排序>2
数据结构·算法
kyle~21 小时前
Schema---数据结构的形式化规则描述
数据结构·windows·microsoft
李小小钦1 天前
D. Storming Arasaka(Codeforces 2238)
c语言·开发语言·数据结构·c++·算法
先吃饱再说1 天前
一篇吃透树的遍历:递归与迭代的完整拆解
数据结构·算法
gugucoding1 天前
31. 【C语言】堆栈与队列的实现
c语言·开发语言·数据结构·链表
ChaoZiLL2 天前
我的数据结构3——链表(link list)
数据结构·链表
王老师青少年编程2 天前
2026年6月GESP真题及题解(C++七级):消消乐
数据结构·c++·算法·真题·gesp·2026年6月