【d53】【Java】【力扣】24.两两交换链表中的节点

思路

定义一个指针cur, 先指向头节点,

1.判断后一个节点是否为空,不为空则交换值,

2.指针向后走两次

代码

/**
 * 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) {
  ListNode cur = head;
            while (cur != null&&cur.next!=null) {
                    int temp=cur.val;
                    cur.val=cur.next.val;
                    cur.next.val=temp;
                    cur = cur.next;
                    cur = cur.next;
            }

            return head;
    }
}

记录

总结

相关推荐
hhw1991121 小时前
c#面试题整理6
java·开发语言·c#
程序视点1 小时前
SpringBoot配置入门
java·spring boot·spring
不知道取啥耶2 小时前
C++ 滑动窗口
数据结构·c++·算法·leetcode
Benaso2 小时前
Java,Golang,Rust 泛型的大体对比小记
java·golang·rust
程序员清风2 小时前
什么时候会考虑用联合索引?如果只有一个条件查就没有建联合索引的必要了么?
java·后端·面试
Seven972 小时前
【设计模式】掌握建造者模式:如何优雅地解决复杂对象创建难题?
java·后端·设计模式
tt5555555555553 小时前
每日一题——三道链表简单题:回文,环形合并有序
数据结构·链表
自在如风。3 小时前
MyBatis-Plus 使用技巧
java·mybatis·mybatis-plus
我想吃烤肉肉3 小时前
leetcode-sql数据库面试题冲刺(高频SQL五十题)
数据库·sql·leetcode
XORE953 小时前
IDEA Generate POJOs.groovy 踩坑小计 | 生成实体 |groovy报错
java·spring·intellij-idea