第三题(入栈出栈序列的合法性)
#include <stdio.h>
#include <stdlib.h>
#include<stdbool.h>
#define MaxSize 50
typedef int ElemType;
bool Judge(char A[])
{
int i=0;
int j=0,k=0;
while(A[i]!='\0')
{
switch(A[i]){
case 'I':j++;break;
case 'O':k++;break;
}
if(k>j)return false;
i++;
}
if(j!=k)return false;
else return true;
}
int main()
{
char *A[50];
gets(A);
printf("当前输入是否合法? %d",Judge(A));
return 0;
}
第四题(利用栈判断链表是否中心对称)
bool dc(LinkList L,int n)
{
int i;
char s[n/2];
LNode *p=L->next;
for(i=0;i<n/2;i++)
{
s[i]=p->data;
p=p->next;
}
i--;
if(n%2==1)
p=p->next;
while(p!=NULL&&s[i]==p->data)
{
i--;
p=p->next;
}
if(i==-1)return true;
return false;
}
第五题(共享栈基本操作)
#include <stdio.h>
#include <stdlib.h>
#include<stdbool.h>
#define MaxSize 50
typedef int ElemType;
typedef struct
{
ElemType data[MaxSize];
int top[2];
} SqStack;
void InitStack(SqStack *S)
{
S->top[0]=-1;
S->top[1]=MaxSize;
}
bool StackEmpty(SqStack *S)
{
if(S->top[1]-S->top[0]==1)return true;
return false;
}
bool Push(SqStack *S,ElemType x,int flag)
{
if(S->top[1]-S->top[0]==1)return false;
if(flag==0)
{
S->data[++S->top[0]]=x;
}
else
{
S->data[--S->top[1]]=x;
}
return true;
}
bool Pop(SqStack *S,ElemType *x,int flag)
{
if((flag==0&&S->top[0]==-1)||(flag==1&&S->top[1]==MaxSize))return false;
if(flag==0)
{
*x=S->data[S->top[0]--];
}
else
{
*x=S->data[S->top[1]++];
}
return true;
}
bool GetTop(SqStack *S,ElemType *x,int flag)
{
if((flag==0&&S->top[0]==-1)||(flag==1&&S->top[1]==MaxSize))return false;
*x=S->data[S->top[flag]];
return true;
}
void PrintStack(SqStack *S,int flag)
{
int i;
if(flag==0)
{
i=0;
printf("打印%d号栈\n",flag);
while(i<=S->top[0])
{
printf("%d ",S->data[i++]);
}
}
else
{
i=S->top[1];
printf("打印%d号栈\n",flag);
while(i<=MaxSize-1)
{
printf("%d ",S->data[i++]);
}
}
printf("\n");
}
int main()
{
SqStack s;
InitStack(&s);
for(int i=1; i<=10; i++)
{
Push(&s,i,0);
}
for(int i=40; i<=50; i++)
{
Push(&s,i,1);
}
printf("将1~10入0号栈,40~50入1号栈\n");
PrintStack(&s,0);
PrintStack(&s,1);
int *t0;
int *t1;
printf("1号栈pop出一个元素\n");
Pop(&s,t1,1);
PrintStack(&s,1);
return 0;
}