(1)设计一个算法,利用顺序栈的基本运算删除栈st中所有值为e的元素(这样的元素可能有多个),并且保持其他元素次序不变。并用相关数据进行测试。
时间: 2023-04-03 12:03:25 浏览: 346
可以回答这个问题。算法如下:
1. 定义一个辅助栈temp,用于存放不等于e的元素。
2. 从栈st中依次取出元素,如果该元素不等于e,则将其压入temp栈中。
3. 遍历完栈st后,将temp栈中的元素依次弹出并压入栈st中,即可删除所有值为e的元素并保持其他元素次序不变。
以下是相关数据测试的代码:
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 100
typedef int ElemType;
typedef struct {
ElemType data[MAXSIZE];
int top;
} SqStack;
void InitStack(SqStack *S) {
S->top = -1;
}
int StackEmpty(SqStack S) {
return S.top == -1;
}
int StackFull(SqStack S) {
return S.top == MAXSIZE - 1;
}
int Push(SqStack *S, ElemType e) {
if (StackFull(*S)) {
return 0;
}
S->data[++S->top] = e;
return 1;
}
int Pop(SqStack *S, ElemType *e) {
if (StackEmpty(*S)) {
return 0;
}
*e = S->data[S->top--];
return 1;
}
int DeleteAll(SqStack *S, ElemType e) {
SqStack temp;
InitStack(&temp);
while (!StackEmpty(*S)) {
ElemType x;
Pop(S, &x);
if (x != e) {
Push(&temp, x);
}
}
while (!StackEmpty(temp)) {
ElemType x;
Pop(&temp, &x);
Push(S, x);
}
return 1;
}
void PrintStack(SqStack S) {
while (!StackEmpty(S)) {
ElemType x;
Pop(&S, &x);
printf("%d ", x);
}
printf("\n");
}
int main() {
SqStack S;
InitStack(&S);
Push(&S, 1);
Push(&S, 2);
Push(&S, 3);
Push(&S, 2);
Push(&S, 4);
Push(&S, 2);
printf("Before delete: ");
PrintStack(S);
DeleteAll(&S, 2);
printf("After delete: ");
PrintStack(S);
return 0;
}
输出结果为:
Before delete: 2 4 2 3 2 1
After delete: 4 3 1