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;
        }
    }
}
相关推荐
2301_8035389510 分钟前
Java读取Word图片的两种实用方法
java·开发语言·word
C+-C资深大佬28 分钟前
SSM 框架(Spring + SpringMVC + MyBatis)
java·spring·mybatis
帅次1 小时前
Android 17 开发者实战:核心更新与应用场景落地指南
android·java·ios·android studio·iphone·android jetpack·webview
Ramble_Naylor1 小时前
东方通(TongWeb)SpringBoot开发指导
java·spring boot
大鹏说大话1 小时前
SQL 排序与分组实战:解决“分组后取最新数据“
android·java·数据库
云烟成雨TD1 小时前
Spring AI Alibaba 1.x 系列【64】 ReactAgent 长期记忆
java·人工智能·spring
quan26311 小时前
20260529,日常开发-数据库主从问题
java·mysql·主从·延迟
JacksonMx2 小时前
@Transactional 最佳实践
java·spring boot·spring·性能优化
Sincerelyplz2 小时前
【AI会议纪要实践】mapReduce、RAG 与结构化输出
java·后端·agent
过期动态2 小时前
【LeetCode 热题 100】接雨水
java·数据结构·算法·leetcode·职场和发展