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;
        }
    }
}
相关推荐
qq_547026179几秒前
Maven 使用指南
java·maven
C++ 老炮儿的技术栈4 分钟前
什么是通信规约
开发语言·数据结构·c++·windows·算法·安全·链表
@大迁世界8 分钟前
TypeScript 的本质并非类型,而是信任
开发语言·前端·javascript·typescript·ecmascript
xiaolyuh1239 分钟前
Arthas修改类(如加日志)的实现原理
java
栗子叶13 分钟前
Java对象创建的过程
java·开发语言·jvm
Amumu1213822 分钟前
React面向组件编程
开发语言·前端·javascript
有一个好名字23 分钟前
力扣-从字符串中移除星号
java·算法·leetcode
IT=>小脑虎23 分钟前
Python零基础衔接进阶知识点【详解版】
开发语言·人工智能·python
wjs202425 分钟前
C 标准库 - `<float.h>》详解
开发语言
zfj32132 分钟前
CyclicBarrier、CountDownLatch、Semaphore 各自的作用和用法区别
java·开发语言·countdownlatch·semaphore·cyclicbarrier