使用linkedlist存储学生信息的代码
时间: 2024-05-01 21:16:10 浏览: 24
以下是使用链表(LinkedList)存储学生信息的示例代码:
```java
class Student {
String name;
int id;
int age;
String major;
public Student(String name, int id, int age, String major) {
this.name = name;
this.id = id;
this.age = age;
this.major = major;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", id=" + id +
", age=" + age +
", major='" + major + '\'' +
'}';
}
}
class Node {
Student data;
Node next;
public Node(Student data) {
this.data = data;
this.next = null;
}
public void displayNode() {
System.out.println(data.toString());
}
}
class LinkedList {
private Node first;
public LinkedList() {
first = null;
}
public boolean isEmpty() {
return (first == null);
}
public void insertFirst(Student data) {
Node newNode = new Node(data);
newNode.next = first;
first = newNode;
}
public Node deleteFirst() {
Node temp = first;
first = first.next;
return temp;
}
public void displayList() {
Node current = first;
while (current != null) {
current.displayNode();
current = current.next;
}
}
}
public class Main {
public static void main(String[] args) {
LinkedList studentList = new LinkedList();
studentList.insertFirst(new Student("Alice", 1001, 20, "Computer Science"));
studentList.insertFirst(new Student("Bob", 1002, 21, "Mathematics"));
studentList.insertFirst(new Student("Charlie", 1003, 19, "Physics"));
studentList.displayList();
}
}
```
在这个示例代码中,我们定义了一个 `Student` 类来表示学生信息,包括姓名、学号、年龄和专业。然后我们定义了一个 `Node` 类来表示链表中的节点,其中包含一个 `Student` 对象和一个指向下一个节点的指针。最后我们定义了一个 `LinkedList` 类来实现链表的基本操作,包括插入、删除和遍历等。在 `Main` 类中,我们创建了一个 `LinkedList` 对象并向其中插入了三个 `Student` 对象,然后打印出整个链表中的所有学生信息。
注意,在实际应用中,我们可能需要根据具体的需求对学生信息进行进一步的扩展和修改,例如添加成绩、联系方式等。另外,为了提高数据访问效率,我们可以使用其他更高效的数据结构来存储学生信息,例如数组、哈希表或者数据库等。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)