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;
        }
    }
}
相关推荐
.格子衫.16 小时前
Spring Boot 原理篇
java·spring boot·后端
多云几多16 小时前
Yudao单体项目 springboot Admin安全验证开启
java·spring boot·spring·springbootadmin
Jabes.yang19 小时前
Java求职面试实战:从Spring Boot到微服务架构的技术探讨
java·数据库·spring boot·微服务·面试·消息队列·互联网大厂
聪明的笨猪猪19 小时前
Java Redis “高可用 — 主从复制”面试清单(含超通俗生活案例与深度理解)
java·经验分享·笔记·面试
执尺量北斗19 小时前
[特殊字符] 基于 Qt + OpenGL 实现的入门级打砖块游戏
开发语言·qt·游戏
夏子曦19 小时前
C#内存管理深度解析:从栈堆原理到高性能编程实践
开发语言·c#
兮动人19 小时前
Spring Bean耗时分析工具
java·后端·spring·bean耗时分析工具
MESSIR2219 小时前
Spring IOC(控制反转)中常用注解
java·spring
摇滚侠19 小时前
Spring Boot 3零基础教程,Demo小结,笔记04
java·spring boot·笔记
笨手笨脚の20 小时前
设计模式-迭代器模式
java·设计模式·迭代器模式·行为型设计模式