实验三:栈和队列
程序代码:
(1):栈
#include<stdio.h>
#include<malloc.h>
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<stdio.h>
#include<malloc.h>
#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
2 1
(2)队列
2 3 -4 6 -5 8 -9 7 -10 20
2 3 6 8 7 20
遇到问题:
1.输出最后一个数值时出错
2.调用函数时实参类型出错
3.输出函数调用出错
4.初始化队列出现错误
5.aa函数出现死循环
解决办法:
1.需将栈底链表的next指向NULL,否则最后一个数值将
随机输出
2.在子函数中使用&h作为实参变量
3.输出循环判断结束应为p!=NULL
4.初始化队列时,采用for循环逐个付给data数组
5.设置i为rear与front之差
实际运行结果
(1)栈
Enter some numbers end by 0
1 2 3 4 0
The remaining numbers are:
4 3 2 1
Pop a number
4
The remaining numbers are:
3 2 1
Pop a number
3
The remaining numbers are:
2 1请按任意键继续. . .
(2)队列
The numbers are:
2 3 -4 6 -5 8 -9 7 -10 20
The numbers are:
2 3 6 8 7 20
请按任意键继续. . .
个人体会:
1.编写程序应力求规范,便于改写。
2.编写程序应该多调试,多修改,有耐心。
3.关于栈的尾应该指向NULL,才能正常输出
4.循环队列的循环方式应该注意。