• 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

  • 相关阅读:
    (原创)sqlite封装库SmartDB1.3发布
    合索引 与 单一列的索引
    Sql中CHARINDEX用法
    Eclipse 的快捷键以及文档注释、多行注释的快捷键
    JAVA 方法或者类的注释快捷键
    关于/r与/n 以及 /r/n 的区别总结
    c#中Split 分离字符以及空格消除方法
    C#生成Guid的几种方式
    MVC ViewBag和ViewData的使用
    软考之高级系统架构设计师(包含历年真题详解+课本教程+论文范文+视频教程)
  • 原文地址:https://www.cnblogs.com/wysAC666/p/9866113.html
Copyright © 2020-2023  润新知