队列和栈

队列:先进先出
栈:先进后出

public
class Test { public static void main(String[] args) { Student s1 = new Student(); s1.setSid(1); s1.setSname("张三"); Student s2 = new Student(); s2.setSid(2); s2.setSname("李四"); Student s3 = new Student(); s3.setSid(3); s3.setSname("李五"); /* SNode n = new SNode(); Link link = new Link(n); SNode n1 = new SNode(); n1.setData(s1); link.InQueue(n1);//入队 SNode n2 = new SNode(); n2.setData(s2); link.InQueue(n2); SNode n3 = new SNode(); n3.setData(s3); link.InQueue(n3); System.out.println(link.Empty()); //循环遍历 List<Student> list1 = link.Selete1(); for (Student stu : list1) { System.out.println(stu.getSid()+" "+stu.getSname()); } List<Student> list = new ArrayList<>(); //出队 while(!link.Empty()){ SNode n9 = link.OutQueue(); list.add(n9.getData()); } for (Student s : list) { System.out.println(s.getSid()+" "+s.getSname()); }*/ SNode n = new SNode(); Link link = new Link(n); SNode n1 = new SNode(); n1.setData(s1); link.Push(n1);//入栈 SNode n2 = new SNode(); n2.setData(s2); link.Push(n2); SNode n3 = new SNode(); n3.setData(s3); link.Push(n3); System.out.println(link.Empty()); List<Student> list = new ArrayList<>(); while(!link.Empty()){ SNode n9 = link.Pop();//出栈 list.add(n9.getData()); } for (Student s : list) { System.out.println(s.getSid()+" "+s.getSname()); } } } class SNode { private SNode next; private Student data; public SNode getNext() { return next; } public void setNext(SNode next) { this.next = next; } public Student getData() { return data; } public void setData(Student data) { this.data = data; } } class Student { private int sid ; private String sname; public int getSid() { return sid; } public void setSid(int sid) { this.sid = sid; } public String getSname() { return sname; } public void setSname(String sname) { this.sname = sname; } } class Link { private SNode head; /* *link构造方法,给变量赋初值 */ public Link(SNode snode){ this.head = snode ; } /* *判断堆栈是否为空 */ public boolean Empty(){ return this.head.getNext()==null; } /* *堆栈添加对象 入栈 */ public void Push(SNode snode){ if(!(this.head.getNext()==null)){ snode.setNext(this.head.getNext()); } this.head.setNext(snode); } /* *堆栈 出栈 */ public SNode Pop() { SNode snode = this.head.getNext(); this.head .setNext(this.head.getNext().getNext()); return snode; } /* *队列 入队 */ public void InQueue(SNode snode){ SNode p = this.head; while(p!=null){ if(p.getNext()==null){ p.setNext(snode); break; } p= p.getNext(); } } /* *队列 出队 */ public SNode OutQueue() { SNode snode = this.head.getNext(); this.head .setNext(this.head.getNext().getNext()); return snode; } /* *遍历输出 */ public List<Student> Selete1(){ List<Student> list = new ArrayList<>(); SNode p = this.head.getNext(); while(p!=null){ list.add(p.getData()); p= p.getNext(); } return list; } }

 

posted @ 2019-06-26 12:02  温碧泉  阅读(151)  评论(0编辑  收藏  举报