Java 单链表简单实现

实现功能并不完全,只有添加,删除,和遍历功能,后续还会继续添加

定义节点属性

class Node{ //定义节点属性
    public int Data;
    public Node next = null;
    public Node(int Data){
        this.Data = Data;
    }
}

定义节点方法

class ListMe {
    Node head = null;//头结点为空
    
    void addNode(int data){ //添加节点
        Node newNode = new Node(data); //创建新节点
        if(head == null){   //如果头结点为空,就让节点作为头结点
            head = newNode;
            return;
        }
        Node temp = head;        
        while(temp.next!=null){ //让节点遍历都最后一个位置
            temp = temp.next;
        }
        temp.next = newNode;   //添加节点
    }
    boolean  delNode(int position){  //删除节点
        if(position>listLength()||position<1){  //如果删除的位置不在指定地方,就返回false
            return false;
        }
        if(position == 1){ //头结点更换
            head = head.next;
            return true;
        }
        int i = 1;
        Node preNode = head;         //前驱节点
        Node curNode = preNode.next; //后一位节点
        while(curNode != null){     //后一位不为空,就遍历查找到指定位置的节点
            if( i == position){  //查找到之后就让前一位直接连到后一位节点位置上
                preNode.next = curNode.next;
                return true;
            }
            preNode = curNode; //节点后推
            curNode = curNode.next; 
            i++;//位置
        }
        return false;
     }
    int listLength(){ //返回链表长度
        int length = 0;
        Node curNode = head;
        while(curNode != null){
            length++;
            curNode = curNode.next;
        }
        return length;
    }
    void print(){  //打印链表内容
        Node curNode = head;
        while(curNode != null){
            System.out.print(curNode.Data+" ");
            curNode = curNode.next;
        }
    }
}

主方法中测试数据

public class Main{
    public static void main(String[] args){
        ListMe a = new ListMe();
        a.addNode(2);
        a.addNode(1);
        a.addNode(5);
        a.addNode(4);
        a.addNode(3);
        a.print();
        System.out.println();
        System.out.println(a.listLength());
        if(a.delNode(1)){
            a.print();
       System.out.println(); System.out.println(a.listLength()); }
else{ System.out.println("异常"); } } }

以下是运行结果

2 1 5 4 3

5

1 5 4 3

4

原文地址:https://www.cnblogs.com/wysAC666/p/9866113.html