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;
        }
    }
}
相关推荐
转转技术团队21 分钟前
加Log就卡?不加Log就瞎?”——这个插件治好了我的精神
java·后端
xcSpark1 小时前
Python基础入门(二)
开发语言·人工智能·python
小杜-coding1 小时前
黑马头条day02
java·spring boot·spring·spring cloud·java-ee·maven·mybatis
谦行1 小时前
前端视角 Java Web 入门手册 5.5:真实世界 Web 开发——控制反转与 @Autowired
java·后端
qw9491 小时前
JVM:JVM与Java体系结构
java·开发语言·jvm
长流小哥1 小时前
Linux 深入浅出信号量:从线程到进程的同步与互斥实战指南
linux·c语言·开发语言·bash
啊QQQQQ1 小时前
设计模式-原型模式
java·设计模式·原型模式
予早1 小时前
Python 冷门魔术方法
开发语言·python
jstart千语1 小时前
【版本控制】git命令使用大全
java·git
李白的粉1 小时前
基于ssm的航空售票系统
java·毕业设计·ssm·课程设计·源代码·航空售票系统