1.回文是指正读反读均相同的字符序列,如“ “abba” ” 和“ “abdba” ” 均是回文,但“ “good” ” 不是回文。试写一个算法判断给定字符序列是否是回文。(提示:将一半字符入栈。)
int isPalindrome(char *t)
{
InitStack(S);
len = strlen(t); //求字符串长度
for(int i = 0; i<len/2; i++) //将一半字符入串
Push(S,t[i]);
if(len%2 != 0)
i++; //长度为奇数,跳过中间字段
while(!EmptyStack(S)) //每弹出一个字符与相应字符比较
{
int tmp = Pop(S);
if(tmp != t[i])
return 0; //不相等返回 0
else
i++;
}
return 1; //比较完毕均相等返回 1
}
2.假设以数组 Q[m] 存放循环队列的元素,同时设置一个标志域名 tag,以 tag0 和 tag1 来区别队头指针 front 和队尾指针 rear 相等时 , 队列状态为“ 空 ” 还是 “ 满 ” 。 试编写与此结构相应的插入 EnQueue 和删除 DeQueue 算法。
typedef struct{
int data[maxSize];
int front; //队首指针
int rear; //队尾指针
int tag;
}SqQueue;
//设 tag 法的循环队列入队算法
int EnQueue(SqQueue &Q, ElemType x)
{
if(Q.front == Q.rear && Q.tag == 1) //两个条件都满足时则队满
return 0;
Q.data[Q.rear] == x;
Q.rear = (Q.rear+1) % MaxSize;
Q.tag = 1;
return 1;
}
//设 tag 法的循环队列出队算法
int DeQueue(SqQueue &Q, ElemType &x)
{
if(Q.front == Q.rear && Q.tag == 0)
return 0;
x = Q.data[Q.front];
Q.front = (Q.front+1) % MaxSize;
Q.tag = 0;
return 1;
}
3.设计一个算法判断输入的表达式中括号是否配对(假设只含有左、右圆括号)
typedef struct LNode{
int data;
struct LNode *next;
}LNode;
bool Match(char exp[], int n)
{
int i = 0; char e;
bool match = true;
LNode *st;
InitStack(st); //初始化栈
while(i < n && match)
{
if(exp[i] == '(') //当前字符为左括号,将其进栈
Push(st,exp[i]);
else if(exp[i] == ')') //当前字符为右括号
{
if(GetTop(st,e) == true) //成功取栈顶元素 e
{
if(e != '(') //栈顶元素不为 ( 时
match = false; //表示不匹配
else //栈顶元素为 )时
Pop(st,e); //将栈顶元素出栈
}
else
match = false; //无法取栈顶元素时表示不匹配
}
i++; //继续处理其他字符
}
if(!StackEmpty(st)) //栈不空时,表示不匹配
match = false;
DestroyStack(st);
return match;
}