考研初试算法题合集2栈和队列/串
#define STACK_SIZE 100
#define STACKINCREAMENT 10
#define error 0
#define ok 1
#define OVERFLOW -2
typedef int SElemtype;
typedef int Status;
typedef char CElemtype;
typedef struct Stack{
SElemtype *base;
SElemtype *top;
int stacksize;
}SqStack;
Status InitStack(SqStack&S)
{
S.base=(ElemType*)malloc(STACK_SIZE*sizeof(ElemType));
if(!S.base)exit(OVERFLOW);
S.top=S.base;
S.stacksize=STACK_SIZE;
return ok;
}
Status Push(SqStack &S,ElemType e)
{
if(S.top-S.base==S.stacksize)
{
S.base=(ElemType*)realloc(S.base,(S.stacksize+STACKINCREAMENT)*sizeof(ElemType));
if(!S.base) return OVERFLOW;
S.top=S.base+S.stacksize;
S.stacksize+=STACKINCREAMENT;
}
*S.top=e;
S.top++;
return ok;
}
typedef int QElemType;
typedef struct QNode{
QElemType data;
struct QNode *next;
}QNode,*QueuePtr;
typedef struct{
QueuePtr front;
QueuePtr rear;
}LinkQueue;
Status EnQueue(LinkQueue &Q,QElemType e){
QNode *p;
p=(QueuePtr)malloc(sizeof(QNode));
if(!p)exit(OVERFLOW);
p->data=e;
p->next=NULL;
Q.rear->next=p;
Q.rear=p;
return ok;
}
Status DeQueue(LinkQueue Q,QElemType &e)
{
QNode *p;
if(Q.rear==Q.front) return error;
p=Q.front->next;
e=p->data;
Q.front->next=p->next;
if(Q.rear==p)
Q.rear=Q.front;
free(p);
return ok;
}
#define MAXSIZE 10
#define OK 1
#define ERROR 0
using namespace std;
typedef int QElemType;
typedef struct
{
QElemType *base;
int front;
int rear;
}SqQueue;
Status InitQueue(SqQueue &Q)
{
Q.base = (QElemType *)malloc(MAXSIZE *sizeof(QElemType));
if (!Q.base) return ERROR;
Q.front = Q.rear = 0;
return OK;
}
Status EnQueue(SqQueue &Q, QElemType e)
{
if ((Q.rear + 1) % MAXSIZE == Q.front) return error;
Q.base[Q.rear] = e;
Q.rear = (Q.rear + 1) % MAXSIZE;
}
Status DeQueue(SqQueue &Q,QElemType &e)
{
if (Q.rear == Q.front) return error;
e=Q.base[Q.front];
Q.front = (Q.front + 1) % MAXSIZE;
return ok;
}
#include<string.h>
#define maxsize 100
typedef struct{
char ch[maxsize];
int len;
}sqtring;
int Index(sqtring S,sqtring P)
{
int i=1,j=1;
while(i<=S.len&&j<=P.len)
{
if(S.ch[i]==P.ch[j]){++i;++j;}
else{i=i-j+2;j=1;}
if(j>P.len)return (i-P.len);
return -1;
}
}
const int max_str_len = 255;
typedef char SString[max_str_len];
int Strlength(SString S){
int len = (int)S[0];
return len;
}
int Get_Index(SString P,int next[])
{
int i,j;
next[i]=1;next[1]=0;j=0;
while(i<=Strlength(P)){
if(j==0||P[i]==P[j]){
++i;++j;next[i]=j;
}
else
j=next[j];
}
}
int Index_KMP(SString S,SString P,int pos,int next[])
{
int i=pos,j=1;
while(i<=Strlength(S)&&j<=Strlength(P))
{
if(j==0||S[i]==P[j]){++i;++j;}
else {j=next[j];}
}
if(j>Strlength(P))return (i-Strlength(P));
return 0;
}