最近,正在看一本《大话数据结构》,发现和我上大学学习的相似度非常高,只不过都是通过C语言进行展示的,之前不是很熟悉开发语言;目前从事java,所以想通过java来实现一次
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;
}
}
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;
}
}
目前只是对单链表进行实现,线性表的顺序存储结构相当于操作数据,暂不进行实现