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;
    }
}
相关推荐
Fanxt_Ja2 天前
【LeetCode】算法详解#15 ---环形链表II
数据结构·算法·leetcode·链表
今后1232 天前
【数据结构】二叉树的概念
数据结构·二叉树
散1122 天前
01数据结构-01背包问题
数据结构
消失的旧时光-19432 天前
Kotlinx.serialization 使用讲解
android·数据结构·android jetpack
Gu_shiwww2 天前
数据结构8——双向链表
c语言·数据结构·python·链表·小白初步
苏小瀚2 天前
[数据结构] 排序
数据结构
_不会dp不改名_2 天前
leetcode_21 合并两个有序链表
算法·leetcode·链表
睡不醒的kun2 天前
leetcode算法刷题的第三十四天
数据结构·c++·算法·leetcode·职场和发展·贪心算法·动态规划
吃着火锅x唱着歌2 天前
LeetCode 978.最长湍流子数组
数据结构·算法·leetcode
Whisper_long2 天前
【数据结构】深入理解堆:概念、应用与实现
数据结构