栈和队列实验报告

  • 格式:docx
  • 大小:17.90 KB
  • 文档页数:6

下载文档原格式

  / 6
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

实验三:栈和队列

程序代码:

(1):栈

#include

#include

typedef struct node

{

int data;

struct node *next;

}node_type;

void pushs(node_type **top)

{

int x;

int i=0;

node_type *p;

printf("Enter some numbers end by 0\n");

scanf("%d",&x);

while(x!=0)

{

p=(node_type*)malloc(sizeof(node_type));

p->data=x;

if(i=0)

{

p->next=NULL;

(*top)=p;

i++;

}

else

{

p->next=(*top);

(*top)=p;

}

scanf("%d",&x);

}

}

void printlst(node_type **top)

{

node_type *p;

p=(*top);

if(p==NULL)

{

printf("There is no bumber\n");

return;

}

printf("The remaining numbers are:\n");

while(p!=NULL)

{

printf("%4d",p->data);

p=p->next;

}

}

int pops(node_type **top)

{

node_type *p;

int x;

if((*top)==NULL)

{

printf("error\n");

return 0;

}

else

{

x=(*top)->data;

printf("\n%d\n",x);

p=(*top);

(*top)=(*top)->next;

return(x);

free(p);

}

}

void main()

{

node_type *h=NULL;

pushs(&h);

printlst(&h);

printf("\nPop a number\n");

pops(&h);

printlst(&h);

printf("\nPop a number\n");

pops(&h);

printlst(&h);

}

(2):队列

#include

#include

#define N 20

typedef struct queue

{ int data[N];

int front, rear;

}queue;

int dequeue(queue *q)

{

if(q->rear==q->front)

return(0);

else

{

q->front=(q->front+1)%N;

return(q->data[q->front]); }

}

int enter(queue *q,int x)

{

if(((q->rear)+1)%N==q->front) return(0);

else

{

q->rear=(q->rear+1)%N;

q->data[q->rear]=x;

return 1;

}

}

void printsl(queue *q)

{

int i;

printf("\nThe numbers are:\n"); i=(q->front+1)%N;

while(i!=(q->rear+1)%N)

{

printf("%4d",q->data[i]);

i=(i+1)%N;

}

printf("\n");

}

void aa(queue *q)

{

int i,j;

int a;

if(q->rear>q->front)

i=q->rear-q->front;

else

i=q->front-q->rear;

for(j=1;j<=i;j++)

{

a=dequeue(q);

if(a>0)

enter(q,a);

}

}

void main()

{

queue *p;

int i;

int a[N]={0,2,3,-4,6,-5,8,-9,7,-10,20};

p=(queue*)malloc(sizeof(queue));

for(i=1;i<=10;i++)

{

p->data[i]=a[i];

}

p->front=0;

p->rear=10;

printsl(p);

aa(p);

printsl(p);

}

典型数据输入:1 2 3 4 0

分析输出:

(1)栈

4 3 2 1

4

3 2 1

3