1. 程式人生 > >java集合框架:淺談如何使用LInkedList實現佇列(Queue)和堆疊(Stack)

java集合框架:淺談如何使用LInkedList實現佇列(Queue)和堆疊(Stack)

Java中的LinkedList 是採用雙向迴圈列表實現的。 利用LinkedList 可以實現棧(stack)、佇列(queue) 感興趣的可以加群:854393687 下面寫兩個例子 學生類: int stuId;

public int getStuId() { return stuId; } public void setStuId(int stuId) { this.stuId = stuId; } 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; } String stuName;

int age;

public Student(){

} public Student(int stuId,String stuName,int age){ this.age = age; this.stuId = stuId; this.stuName = stuName; } public String toString() {

return (“學生姓名:”+this.stuName+“學生年齡”+this.age+“學生編號”+this.stuId);

} 佇列 自定義方法實現LInkedList LinkedList lists =new LinkedList();

public void push(Object object){ lists.addLast(object); } public Object pop(){ return lists.removeFirst(); } 實現方法 System.out.println(“在佇列中新增物件”); MyQuene quene = new MyQuene(); quene.push(new Student(1,“學生1”,20)); quene.push(new Student(2,“學生2”,21)); quene.push(new Student(3,“學生3”,23)); for (Object object : quene.lists) { Student student = (Student)object; System.out.println(student.toString()); } System.out.println(“在佇列中刪除物件”); quene.pop(); for (Object object : quene.lists) { Student student = (Student)object; System.out.println(student.toString()); }

堆疊:

自定義方法,並實現

LinkedList lists =new LinkedList();

public void push(Object object){ lists.addFirst(object); }

public Object pop(){ return lists.removeLast(); } System.out.println(“在佇列中新增物件”); MyStack Stack = new MyStack(); Stack.push(new Student(1,“學生1”,20)); Stack.push(new Student(2,“學生2”,21)); Stack.push(new Student(3,“學生3”,23)); for (Object object : Stack.lists) { Student student = (Student)object; System.out.println(student.toString()); } System.out.println(“在佇列中刪除物件”); Stack.pop(); for (Object object : Stack.lists) { Student student = (Student)object; System.out.println(student.toString()); } 感興趣的可以加群:854393687