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;
        }
    }
}
相关推荐
狼爷7 小时前
吃透 Java Function 接口,搞定 99% 的 Stream 场景
java·函数式编程
祎雪双十Gy11 小时前
从 DataX 的配置加载说起:我用 FastJson2 做了一个轻量级动态配置管理库
java·后端
小锋java123411 小时前
分享一套锋哥原创的SpringBoot4+Vue3宠物领养网站系统
java
考虑考虑14 小时前
Java实现hmacsha1加密算法
java·后端·java ee
掉鱼的猫15 小时前
Spring Boot → Solon 注解迁移实战指南:一张对照表说清楚
java·spring boot
plainGeekDev15 小时前
广播接收器 → Flow + Lifecycle
android·java·kotlin
plainGeekDev15 小时前
EventBus → SharedFlow
android·java·kotlin
带刺的坐椅15 小时前
Spring Boot → Solon 注解迁移实战指南:一张对照表说清楚
java·springboot·web·solon
用户37215742613516 小时前
Java 将一个 PPT 文档拆分为多个文件
java
人活一口气1 天前
Spring Boot与AIGC的完美结合:从零搭建智能内容生成平台
java·spring boot·aigc