具体要求:
设计学生列表类(StudentList),该类内部使用单向链表存放多个学生信息。
同时,该类提供增删改查方法进行学生信息的管理。
节点类(Node);学生类(StudentInfo)
学生集合类中提供的方法:
boolean addData(StudentInfo info)
StudentInfo removeData(int studentId)
boolean changeData(StudentInfo info)
StudentInfo getData(int studentId)
StudentList类
public class StudentList {
private Node head;
public boolean addData(StudentInfo info) {
if (head == null) {
head = new Node(info, null);
return true;
}
Node node = head;
boolean flag = true;
while (node.getNext() != null) {
if (node.getInfo().getId() == info.getId()) {
flag = false;
break;
}
node = node.getNext();
}
if (flag) {
if (node.getInfo().getId() != info.getId()) {
node.setNext(new Node(info, null));
return true;
}
}
return false;
}
public StudentInfo removeData(int studentId) {
StudentInfo info = null;
if (head == null) {
return null;
}
if (head.getInfo().getId() == studentId) {
info = head.getInfo();
head = head.getNext();
return info;
}
Node node = head;
while (node.getNext() != null && node.getNext().getInfo().getId() != studentId) {
node = node.getNext();
}
if (node.getNext() == null) {
return null;
}
info = node.getNext().getInfo();
node.setNext(node.getNext().getNext());
return info;
}
public boolean changeData(StudentInfo info) {
if (head == null) {
return false;
}
Node node = findNodeById(info.getId());
if (node == null) {
return false;
}
node.setInfo(info);
return true;
}
private Node findNodeById(int studentId) {
Node node = head;
while (node != null && node.getInfo().getId() != studentId) {
node = node.getNext();
}
return node;
}
public StudentInfo getData(int studentId) {
Node node = findNodeById(studentId);
if (node == null) {
return null;
}
return node.getInfo();
}
public void showAllStudents() {
System.out.println("---------------------");
if (head == null) {
System.out.println("没有数据");
return;
}
Node node = head;
while (node != null) {
System.out.println(node.getInfo());
node = node.getNext();
}
}
}
StudentInfo类(为了方便查看,已去掉getter和setter方法):
public class StudentInfo {
private int id;
private String name;
private int age;
public StudentInfo(int id, String name, int age) {
super();
this.id = id;
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "student[id=" + id + ",name=" + name + ",age=" + age + "]";
}
}
Node类(为了方便查看,已去掉getter和setter方法):
public class Node {
private StudentInfo info;
private Node next;
public Node() {
super();
}
public Node(StudentInfo info, Node next) {
super();
this.info = info;
this.next = next;
}
}