数据结构题目:队列
题目:链式队列的基本操作
将从键盘输入的一系列字符存储到链式队列中,当输入的字符为’0’时,执行出队操作并将出队元素打印到屏幕上;当输入的字符为’@’时,队列中剩余所有元素依次出队并打印到屏幕上;当输入其他字符时,字符入队。
c:
#include "stdio.h"
#include "malloc.h"
#define MAXSIZE 64
typedef struct{
char data[MAXSIZE];
int front;
int rear;
}squlink;
void QueueInit(squlink *q)
{
q->front = 0;
q->rear = 0;
}
bool EmptyQueue(squlink *q)
{
if(q->front == q->rear)
return (true);
else
return (false);
}
bool FullQueue(squlink *q)
{
if((q->rear + 1) % MAXSIZE == q->front)
return (true);
else
return (false);
}
char EnQueue(squlink *q, char e)
{
if((q->rear + 1) % MAXSIZE == q->front)
return (-1);
q->rear = (q->rear + 1) % MAXSIZE;
q->data[q->rear] = e;
return 0;
}
char DeQueue(squlink *q)
{
if(q->rear == q->front)
return (-1);
q->front = (q->front +1) % MAXSIZE;
return (q->data[q->front]);
}
int main()
{
char x,i;
squlink q;
QueueInit(&q);
printf("请输入x\n");
while(x=getchar(),x-'#')
{
switch(x)
{
case '0':
{
if(EmptyQueue(&q))
{
printf("队列为空\n");
break;
}
else
{
i=DeQueue(&q);
printf("%c\n",i);
break;
}
}
case '@':
{
if(EmptyQueue(&q))
{
printf("队列为空\n");
break;
}
else
{
while(!EmptyQueue(&q))
{
i=DeQueue(&q);
printf("%c",i);
}
printf("\n");
break;
}
}
case '\n': break;
default : EnQueue(&q,x);
}
}
return 0;
}
java:
import java.util.Scanner;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
/**
*@author movis
*/
public class Main {
public static void main(String[] args) throws Exception {
String input = null;
char c;
String flag = "Y"; //用来控制是否继续
Scanner in = new Scanner(System.in);
BlockingQueue<Character> sq = new LinkedBlockingQueue<Character>();
do {
System.out.println("请从键盘输入字符:");
input = in.nextLine();
while(input.length() > 1) {
System.out.println("请输入单字符,请重新输入:");
input = in.nextLine();
}
c = input.charAt(0);
while(c != '@') {
if(c == '0') {
System.out.println("出队:"+sq.poll());
}else {
sq.put(c);
}
System.out.println("请从键盘输入字符:");
input = in.nextLine();
while(input.length() > 1) {
System.out.println("请输入单字符,请重新输入:");
input = in.nextLine();
}
c = input.charAt(0);
}
System.out.print("打印队列:");
while(sq.peek() != null){
System.out.print(sq.poll());
}
System.out.println("\n是否继续?请输入Y(继续)或N(不继续):");
flag = in.nextLine();
while(!flag.equals("Y") && !flag.equals("N")) {
System.out.println("输入错误,请输入Y(继续)或N(不继续):");
flag = in.nextLine();
}
}while(flag.equals("Y"));
in.close();
}
}