Student类:
package com.linkedlist;
public class Student {
private String stuNum;
private String stuName;
private int age;
public Student(String stuNum, String stuName, int age) {
this.stuNum = stuNum;
this.stuName = stuName;
this.age = age;
}
public String getStuNum() {
return stuNum;
}
public void setStuNum(String stuNum) {
this.stuNum = stuNum;
}
public String getStuName() {
return stuName;
}
public void setStuName(String stuName) {
this.stuName = stuName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "[学号:" + stuNum + ", 姓名:" + stuName + ", 年龄:" + age + "]";
}
}
LinkedListDemo2类:
Java
package com.linkedlist;
import java.util.LinkedList;
public class LinkedListDemo2 {
public static void main(String[] args) {
LinkedList<Student> stuList = new LinkedList<Student>();
Student stu1 = new Student("001", "Mike", 18);
Student stu2 = new Student("002", "Jack", 20);
Student stu3 = new Student("003", "Lucy", 19);
// 将学生添加到链表,使用push完成
// LinkedList实现List接口的同时,也实现了Queue接口
// push和pop就是针对Queue进行添加和取出数据的操作的
stuList.push(stu1);
stuList.push(stu2);
stuList.push(stu3);
System.out.println("链表为:" + stuList);
// 弹出一个元素,这里可以把链表看成一个容器,先加入到链表的数据后弹出
// 依据的原则数先进后出,后进先出
System.out.println("弹出的数据为:" + stuList.pop());
System.out.println("调用pop()方法后的链表为:\n" + stuList);
// peek()方法获取并不移除元素
System.out.println("调用peek()方法的数据为:" + stuList.peek());
System.out.println("调用peek()方法后的链表为:\n" + stuList);
// 再次调用pop()方法,发现调用pop()方法后数据从链表中移除了,而peek()方法不会
System.out.println("再次调用pop()方法" + stuList.pop());
System.out.println("再次调用pop()方法后的链表为:\n" + stuList);
// 在链表中再重新添加元素
stuList.push(stu2);
stuList.push(stu3);
System.out.println("再次添加元素后的链表为:\n" + stuList);
// 调用poll()方法
System.out.println("调用poll()方法输出元素" + stuList.poll());
// 调用poll()方法将获取元素的同时从链表中删除了元素
System.out.println("调用poll()方法后的链表为:\n" + stuList);
}
}
运行结果为: