Java原地逆置链表

java 复制代码
public class Solution {
    public static void main(String[] args){
        ListNode ls = new ListNode();
        ls.addNode(10);
        ls.addNode(20);
        ls.addNode(30);
        ls.printLN();
        System.out.println("After reverse..");
        ls.reverse();
        ls.printLN();
    }
}
class Node{
    int val;
    Node next;
    static int count = 0;
    public Node(int data){
        this.val = data;
        next = null;
    }
}
class ListNode{
    Node head = new Node(0);  // headNode-no val
    public void addNode(int data){
        Node temp = head;
        Node newNode = new Node(data);
        while(temp.next != null){
            temp = temp.next;
        }
        temp.next = newNode;
        Node.count++;
        System.out.println("already have nodes " + Node.count);
    }
    public void reverse(){
        Node current = this.head.next;
        Node nextNode = null;
        int count = 1;      // 不需要创建一个新的链表以实现头插法,记录第一个头插的节点,并使其next域指向null
        while(current != null){
            System.out.println(current.val);
            nextNode = current.next;
            current.next = head.next;
            head.next = current;
            if(count ==1 ){ // 第一个头插法的节点需要将指针域置为null
                current.next = null;
            }
            count++;
            current = nextNode;
        }
    }
    public void printLN(){
        Node temp = this.head.next;
        while(temp != null){
            System.out.println(temp.val);
            temp = temp.next;
        }
    }
}
相关推荐
likerhood5 分钟前
java中的return this、链式编程和Builder模式
java·开发语言
spring2997926 分钟前
Spring Boot 实战篇(四):实现用户登录与注册功能
java·spring boot·后端
原来是猿35 分钟前
Linux线程同步与互斥(三):POSIX信号量与环形队列生产者消费者模型
linux·运维·服务器·开发语言
未来转换39 分钟前
基于A2A协议的生产应用实践指南(Java)
java·开发语言·算法·agent
Rust语言中文社区41 分钟前
【Rust日报】Clone:像进程一样 fork 虚拟机的 Rust KVM VMM
开发语言·后端·rust
求知也求真佳1 小时前
S02|工具使用:让 Agent 真正会干活,添加工具
开发语言·agent
后端漫漫1 小时前
Redis 配置文件与服务功能
java·redis
Dwzun1 小时前
基于Java+SpringBoot+Vue的校园二手物品置换系统设计与实现【附源码+文档+部署视频+讲解】
java·开发语言·spring boot
charlie1145141911 小时前
嵌入式Linux驱动开发(3)——内核模块机制 - Linux 的插件系统
linux·运维·开发语言·驱动开发·嵌入式硬件·学习
polaris06301 小时前
Spring Boot 项目开发流程全解析
java·spring boot·log4j