搜索
写经验 领红包
 > 娱乐

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;    }}

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

一步一个脚印

本文内容由小媛整理编辑!