2019-01-12 回答
class linkedlist //定义双项链表 { char data; linkedlist back; linkedlist forward; } interface access //定义从队列和栈存取操作的接口 { void put(char c); char get(); } class queue implements access //定义队列类 { private linkedlist qhead=new linkedlist(); private linkedlist qrear=qhead; //初始化队头和队尾 public void put(char c) //实现向队列存数的方法 { qrear.forward=new linkedlist(); qrear.forward.data=c; qrear.forward.back=qrear; qrear=qrear.forward; } public char get() //实现从队列取数的方法 { if(qhead!=qrear) //如果队列不为空则取数 { qhead.forward.back=null; qhead=qhead.forward; return qhead.data; } else { system.out.println("the queue is empty! "); return '\0'; } } } class stack implements access //定义栈类 { private linkedlist bottom=new linkedlist(); private linkedlist top=bottom; //初始化栈顶与斩底 public void put(char c) //实现从栈中存数的方法 { top.forward=new linkedlist(); top.forward.data=c; top.forward.back=top; top=top.forward; } public char get() //实现从栈中取数的方法 { if(top!=bottom) //如果栈不为空则取数 { char ch=top.data; top.back.forward=null; top=top.back; return ch; } else { system.out.println("the stack is empty! "); return '\0'; } } } public class stackqueue { public static void main(string[] args) { char ch; queue q=new queue(); //创建一个队列q stack s=new stack(); //创建一个栈s q.put('x'); q.put('y'); q.put('z'); //向队列q存入3个字符 s.put('x'); s.put('y'); s.put('z'); //向栈s存入3个字符 system.out.println("queue: "); if((ch=q.get())!='\0') system.out.println(ch); if((ch=q.get())!='\0') system.out.println(ch); if((ch=q.get())!='\0') system.out.println(ch); if((ch=q.get())!='\0') system.out.println(ch); //从队列q中取数并显示 system.out.println("stack: "); if((ch=s.get())!='\0') system.out.println(ch); if((ch=s.get())!='\0') system.out.println(ch); if((ch=s.get())!='\0') system.out.println(ch); if((ch=s.get())!='\0') system.out.println(ch); //从栈s中取数并显示 } } 引自: http://wenwen.soso.com/z/q104863.htm?ch=w.xg.ll