我有一个我写的LinkedList类,我有另一类学生。每个学生都有ID,姓名,GPA ......
如何将这些变量作为1个元素添加到链表中。好像我需要在该链表中搜索一个元素,我可以显示该学生的所有信息。
如果您需要进一步说明,请复制一些代码。
答案 0 :(得分:2)
遵循java.util.List示例:
List<Student> roster = new ArrayList<Student>();
只需替换您自己的参考和实现类:
YourLinkedList roster = new YourLinkedList();
Student s = new Student();
roster.add(s);
至于搜索给定的Student实例,我会写一个Iterator,它可以带一个Comarator并返回链接列表的过滤版本。
答案 1 :(得分:1)
我猜你有Student
和MyLinkedList
类,现在你想要使用它们,因为你的链表可能只支持整数项。你可以使用这样的东西
public class Student {
private int id;
private String name;
private double gpa;
//getters and setters...
}
现在您需要添加Student
类作为链接列表中节点的信息:
public class MyLinkedList {
class MyNode {
private Student student;
private MyNode next;
public MyNode(Student student) {
this.student = student;
this.next = null;
}
public Student getStudent() {
return this.student;
}
}
private MyNode root;
private int size;
public MyLinkedList {
this.root = null;
}
public void add(Student student) {
//this is just one way to implement the insert method
//you can rewrite to use your own implementation
MyNode node = new MyNode(student);
if (root == null) {
root = node;
} else {
MyNode currentNode = root;
while (currentNode.next != null) {
currentNode = currentNode.next;
}
currentNode.next = node;
}
size++;
}
public void printData() {
//method used to print the content of the linked list
MyNode currentNode = root;
while (currentNode != null) {
Student student = currentNode.getStudent();
System.out.println("Id: " + student.getId + " Name: " + student.getName());
currentNode = currentNode.next;
}
}
}
通过这种方式,您可以使用Student
类实现新的链接列表。我们试试代码:
public static void main(String args[]) {
MyLinkedList mll = new MyLinkedList;
Student student;
student = new Student();
student.setId(1);
student.setName("Luiggi");
mll.add(student);
student = new Student();
student.setId(2);
student.setName("Mendoza");
mll.add(student);
mll.printData();
}
这只是一个示例,您可以改进代码,但是您可以获得主要想法。