java单链表学生系统增删改代码,学生类中带有学号,并重写方法使得链表按学号排序
时间: 2024-10-04 18:04:05 浏览: 32
1800+行代码学生信息管理系统,c++实现+文件读写+单链表+排序
4星 · 用户满意度95%
在Java中,我们可以创建一个Student类,包含学号属性,然后定义一个双向链表(如LinkedList)结构来存储学生信息。这里我会提供一个基本的增删改查操作以及链表按学号排序的示例:
首先,定义Student类:
```java
public class Student {
private int studentId;
private String name;
public Student(int id, String name) {
this.studentId = id;
this.name = name;
}
// getters and setters for studentId and name
public int getStudentId() { return studentId; }
public void setStudentId(int studentId) { this.studentId = studentId; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
@Override
public String toString() {
return "Student{" +
"studentId=" + studentId +
", name='" + name + '\'' +
'}';
}
}
```
接下来,定义一个双向链表节点,包含Student对象:
```java
class Node {
Student student;
Node prev;
Node next;
public Node(Student student, Node prev, Node next) {
this.student = student;
this.prev = prev;
this.next = next;
}
}
// 双向链表类
public class StudentList {
private Node head;
private Node tail;
// 添加、删除和修改操作...
public void addStudent(Student student) {
if (head == null) {
head = new Node(student, null, null);
tail = head;
} else {
Node current = head;
while (current.next != null && current.next.getStudentId() < student.getStudentId()) {
current = current.next;
}
if (current.next != null) {
current.next.prev = current;
}
current.next = new Node(student, current, current.next);
if (current.next == tail) {
tail = current.next;
}
}
}
// 删除操作...
public void removeStudent(int id) {
// 略
}
// 修改操作...
public void updateStudent(int id, String newName) {
// 略
}
// 按学号排序并打印链表
public void sortAndPrintStudents() {
if (head == null) {
System.out.println("链表为空");
return;
}
Collections.sort(head, new Comparator<Student>() {
@Override
public int compare(Student s1, Student s2) {
return Integer.compare(s1.getStudentId(), s2.getStudentId());
}
});
printList();
}
private void printList() {
Node current = head;
while (current != null) {
System.out.println(current.student);
current = current.next;
}
}
}
```
阅读全文