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;
        }
    }
}
相关推荐
zhuiQiuMX14 分钟前
笔试阶段性心得总结
java·python
星沁城1 小时前
236. 二叉树的最近公共祖先
java·数据结构·leetcode·二叉树
oliveira-time2 小时前
Java 1.8(也称为Java 8)
java·开发语言
极小狐4 小时前
如何使用极狐GitLab 软件包仓库功能托管 maven?
java·运维·数据库·安全·c#·gitlab·maven
.生产的驴4 小时前
SpringBoot 集成滑块验证码AJ-Captcha行为验证码 Redis分布式 接口限流 防爬虫
java·spring boot·redis·分布式·后端·爬虫·tomcat
野犬寒鸦6 小时前
MySQL索引使用规则详解:从设计到优化的完整指南
java·数据库·后端·sql·mysql
思考的橙子6 小时前
Springboot之会话技术
java·spring boot·后端
钰爱&6 小时前
【Linux】POSIX 线程信号量与互斥锁▲
java·开发语言·jvm
yt948327 小时前
Matlab实现绘制任意自由曲线
开发语言·matlab
黑匣子~8 小时前
java集成telegram机器人
java·python·机器人·telegram