C语言 数据结构 实验二
8583 - 顺序栈的基本操作
#include <malloc.h>
#include <stdio.h>
#define OK 1
#define ERROR 0
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
typedef int SElemType;
typedef int Status;
struct SqStack
{
SElemType *base;
SElemType *top;
int stacksize;
};
Status InitStack(SqStack &S)
{
S.base = (SElemType *)malloc(sizeof(SElemType) * STACK_INIT_SIZE);
if(!S.base)
{
return ERROR;
}
S.top = S.base;
S.stacksize = STACK_INIT_SIZE;
return OK;
}
Status Push(SqStack &S, SElemType e)
{
if(S.top-S.base >= S.stacksize)
{
S.base = (SElemType *)realloc(S.base, sizeof(SElemType) * (S.stacksize+STACKINCREMENT));
if(!S.base)
{
return ERROR;
}
S.top = S.base+S.stacksize;
S.stacksize += STACKINCREMENT;
}
*(S.top++) = e;
return OK;
}
Status Pop(SqStack &S, SElemType &e)
{
if(S.top == S.base)
{
return ERROR;
}
e = *(--S.top);
return OK;
}
Status GetTop(SqStack S, SElemType &e)
{
if(S.top-S.base == 0)
{
return ERROR;
}
e = *(--S.top);
S.top++;
return OK;
}
int StackLength(SqStack S)
{
return S.top-S.base;
}
Status StackTraverse(SqStack S)
{
SElemType *p = (SElemType *)malloc(sizeof(SElemType));
p = S.top;
if(S.top-S.base == 0) printf("The Stack is Empty!");
else
{
printf("The Stack is: ");
p--;
while(p+1 != S.base)
{
printf("%d ", *p);
p--;
}
}
printf("\n");
return OK;
}
int main()
{
int a;
SqStack S;
SElemType x, e;
if(InitStack(S))
{
printf("A Stack Has Created.\n");
}
while(1)
{
printf("1:Push \n2:Pop \n3:Get the Top \n4:Return the Length of the Stack\n5:Load the Stack\n0:Exit\nPlease choose:\n");
scanf("%d", &a);
switch(a)
{
case 1: scanf("%d", &x);
if(!Push(S, x)) printf("Push Error!\n");
else printf("The Element %d is Successfully Pushed!\n", x);
break;
case 2: if(!Pop(S, e)) printf("Pop Error!\n");
else printf("The Element %d is Successfully Poped!\n", e);
break;
case 3: if(!GetTop(S, e))printf("Get Top Error!\n");
else printf("The Top Element is %d!\n", e);
break;
case 4: printf("The Length of the Stack is %d!\n", StackLength(S));
break;
case 5: StackTraverse(S);
break;
case 0: return 1;
}
}
}
8584 - 循环队列的基本操作
#include <malloc.h>
#include <stdio.h>
#define OK 1
#define ERROR 0
#define MAXQSIZE 100
typedef int QElemType;
typedef int Status;
typedef struct
{
QElemType *base;
int front;
int rear;
}SqQueue;
Status InitQueue(SqQueue &Q)
{
Q.base = (QElemType *)malloc(sizeof(QElemType) * MAXQSIZE);
if(!Q.base)
{
return ERROR;
}
Q.front = Q.rear = 0;
return OK;
}
Status EnQueue(SqQueue &Q, QElemType e)
{
if((Q.rear+1)%MAXQSIZE == Q.front)
{
return ERROR;
}
Q.base[Q.rear] = e;
Q.rear = (Q.rear+1)%MAXQSIZE;
return OK;
}
Status DeQueue(SqQueue &Q, QElemType &e)
{
if(Q.rear == Q.front)
{
return ERROR;
}
e = Q.base[Q.front];
Q.front = (Q.front+1)%MAXQSIZE;
return OK;
}
Status GetHead(SqQueue Q, QElemType &e)
{
if(Q.rear == Q.front)
{
return ERROR;
}
e = Q.base[Q.front];
return OK;
}
int QueueLength(SqQueue Q)
{
return