龙空技术网

数据结构之单链表Java实现

远方老表 117

前言:

目前姐妹们对“用java实现单链表”大致比较关切,朋友们都需要知道一些“用java实现单链表”的相关资讯。那么小编同时在网摘上网罗了一些对于“用java实现单链表””的相关文章,希望小伙伴们能喜欢,你们快快来学习一下吧!

最近,正在看一本《大话数据库结构》,发现和我上大学学习的相似度非常高,只不过都是通过C语言进行展示的,之前不是很熟悉开发语言;目前从事java,所以想通过java来实现一次

1.Student类:

public class Student {    private String name;    private Student next;     public String getName() {        return name;    }     public void setName(String name) {        this.name = name;    }     public Student getNext() {        return next;    }     public void setNext(Student next) {        this.next = next;    }}

2.操作Student类的链表类:

public class SingleList {    private Student student = new Student();    //相当于头结点    private Student s = student;    private int length = 0;      public void add(Student stu){        s.setNext(stu);        s = s.getNext();        ++length;    }     public void getAll(){        Student node = student;        while ((node = node.getNext()) != null){            System.out.println(node.getName());        }    }     public Student get(int i){        Student node = student;         if(i > length){            return null;        }        int j = 0;        while(i < length && j < i){            j++;            node = node.getNext();        }        return node;    }    public Student get(){        return s;    }    public Student remove(){        Student node = student;        int j = 0;        while(j < length-1){            j++;            node = node.getNext();        }        Student ele = node.getNext();        node.setNext(null);        s = node;        length--;        return  ele;    }    public void add(int i, Student stu){        Student node = student;        int j = 0;        if(i > length){            System.out.println("位置超过链表最大位置");        }else if(i == length){    //如果在末尾增加            add(stu);        }else{            while(j < i){                j++;                node = node.getNext();            }            stu.setNext(node.getNext());            node.setNext(stu);            length++;        }    }    public Student remove(int i){        if(i > length){            return null;        }else if(i == length){            return remove();        }else{            Student node = student;            int j = 0;            while(j < i-1){                j++;                node = node.getNext();      //node最大为第i-1个位置            }            Student stu = node.getNext();   //stu为第i个位置            node.setNext(stu.getNext());            length--;            return stu;        }    }    public Student getStudent() {        return student;    }    public void setStudent(Student student) {        this.student = student;    }    public int getLength() {        return length;    }    public void setLength(int length) {        this.length = length;    }    public Student getS() {        return s;    }    public void setS(Student s) {        this.s = s;    }}

前只是对单链表进行实现,线性表的顺序存储结构相当于操作数据,暂不进行实现

一步一个脚印

标签: #用java实现单链表