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;
        }
    }
}
相关推荐
趣知岛1 小时前
初识Java
java·开发语言
步菲3 小时前
springboot canche 无法避免Null key错误, Null key returned for cache operation
java·开发语言·spring boot
毕设源码-朱学姐3 小时前
【开题答辩全过程】以 基于SpringBoot的中医理疗就诊系统为例,包含答辩的问题和答案
java·spring boot·后端
2201_757830877 小时前
全局异常处理器
java
知远同学8 小时前
Anaconda的安装使用(为python管理虚拟环境)
开发语言·python
小徐Chao努力8 小时前
【Langchain4j-Java AI开发】09-Agent智能体工作流
java·开发语言·人工智能
风筝在晴天搁浅8 小时前
hot100 25.K个一组翻转链表
数据结构·链表
CoderCodingNo8 小时前
【GESP】C++五级真题(贪心和剪枝思想) luogu-B3930 [GESP202312 五级] 烹饪问题
开发语言·c++·剪枝
Coder_Boy_8 小时前
SpringAI与LangChain4j的智能应用-(理论篇3)
java·人工智能·spring boot·langchain
kylezhao20198 小时前
第1章:第一节 开发环境搭建(工控场景最优配置)
开发语言·c#