用c语言编写程序:1.利用“数组”作为存储结构方法实现“堆栈”的基本操作,包括:创建堆栈、入栈、出栈、空栈、满栈等操作。 2.利用堆栈完成,将一组输入的数据逆序输出。依次入栈的数据如下:abcdef 依次出栈的数据如下:fedcba 3.利用“数组”作为存储结构方法实现“队列”的基本操作,包括:创建队列、入队列、出队列、队列满、队列空等基本操作 4.利用“堆栈”和“队列”,对输入的一组“字符串”判断是否“回文”
时间: 2023-09-13 12:03:48 浏览: 104
好的,以下是对你的问题的回答:
1. 实现堆栈的基本操作代码如下:
```c
#include <stdio.h>
#define MAXSIZE 10
int stack[MAXSIZE];
int top = -1;
void createStack()
{
top = -1;
}
int isFull()
{
if (top == MAXSIZE - 1)
return 1;
else
return 0;
}
int isEmpty()
{
if (top == -1)
return 1;
else
return 0;
}
void push(int data)
{
if (isFull())
printf("Stack is full\n");
else
stack[++top] = data;
}
int pop()
{
if (isEmpty())
{
printf("Stack is empty\n");
return -1;
}
else
return stack[top--];
}
```
2. 将一组输入的数据逆序输出的代码如下:
```c
#include <stdio.h>
#include <string.h>
#define MAXSIZE 10
int stack[MAXSIZE];
int top = -1;
void createStack()
{
top = -1;
}
int isFull()
{
if (top == MAXSIZE - 1)
return 1;
else
return 0;
}
int isEmpty()
{
if (top == -1)
return 1;
else
return 0;
}
void push(int data)
{
if (isFull())
printf("Stack is full\n");
else
stack[++top] = data;
}
int pop()
{
if (isEmpty())
{
printf("Stack is empty\n");
return -1;
}
else
return stack[top--];
}
int main()
{
char s[] = "abcdef";
int len = strlen(s);
createStack();
for (int i = 0; i < len; i++)
push(s[i]);
printf("Original string: %s\n", s);
printf("Reversed string: ");
while (!isEmpty())
printf("%c", pop());
printf("\n");
return 0;
}
```
3. 实现队列的基本操作代码如下:
```c
#include <stdio.h>
#define MAXSIZE 10
int queue[MAXSIZE];
int front = -1;
int rear = -1;
void createQueue()
{
front = rear = -1;
}
int isFull()
{
if ((front == 0 && rear == MAXSIZE - 1) || (rear == front - 1))
return 1;
else
return 0;
}
int isEmpty()
{
if (front == -1)
return 1;
else
return 0;
}
void enqueue(int data)
{
if (isFull())
printf("Queue is full\n");
else
{
if (front == -1)
front = 0;
rear = (rear + 1) % MAXSIZE;
queue[rear] = data;
}
}
int dequeue()
{
if (isEmpty())
{
printf("Queue is empty\n");
return -1;
}
else
{
int data = queue[front];
if (front == rear)
front = rear = -1;
else
front = (front + 1) % MAXSIZE;
return data;
}
}
```
4. 判断字符串是否回文的代码如下:
```c
#include <stdio.h>
#include <string.h>
#define MAXSIZE 10
int stack[MAXSIZE];
int top = -1;
void createStack()
{
top = -1;
}
int isFull()
{
if (top == MAXSIZE - 1)
return 1;
else
return 0;
}
int isEmpty()
{
if (top == -1)
return 1;
else
return 0;
}
void push(int data)
{
if (isFull())
printf("Stack is full\n");
else
stack[++top] = data;
}
int pop()
{
if (isEmpty())
{
printf("Stack is empty\n");
return -1;
}
else
return stack[top--];
}
int main()
{
char s[] = "abccba";
int len = strlen(s);
int i;
for (i = 0; i < len / 2; i++)
push(s[i]);
if (len % 2 != 0)
i++;
while (s[i] != '\0')
{
if (pop() != s[i])
{
printf("%s is not palindrome\n", s);
return 0;
}
i++;
}
printf("%s is palindrome\n", s);
return 0;
}
```
阅读全文