用C语言定义顺序栈、链栈,完成栈的基本操作:建立空栈、入栈、出栈、取栈顶元素、判断栈中元素个数、置空栈;
时间: 2024-11-06 22:20:22 浏览: 26
在C语言中,我们可以分别用数组(顺序存储)和链表(动态存储)的方式来定义栈。
**顺序栈(Array Stack)**:
```c
#include <stdio.h>
#define MAX_SIZE 100
typedef int ElementType;
typedef struct {
ElementType data[MAX_SIZE];
int top; // 栈顶指针
} SeqStack;
// 初始化空栈
void initSeqStack(SeqStack* s) {
s->top = -1;
}
// 入栈 (Push)
void push(SeqStack* s, ElementType e) {
if (s->top == MAX_SIZE - 1) {
printf("Stack overflow.\n");
} else {
s->data[++(s->top)] = e;
}
}
// 出栈 (Pop)
ElementType pop(SeqStack* s) {
if (s->top == -1) {
printf("Stack underflow.\n");
return 0; // 返回默认值,表示栈为空
} else {
return s->data[s->top--];
}
}
// 取栈顶元素 (Top)
ElementType getTop(SeqStack* s) {
if (s->top == -1) {
printf("Stack is empty.\n");
return 0; // 返回默认值,表示栈为空
} else {
return s->data[s->top];
}
}
// 判断栈中元素个数 (IsEmpty)
int isEmpty(SeqStack* s) {
return s->top == -1;
}
// 置空栈 (Clear)
void clearSeqStack(SeqStack* s) {
s->top = -1;
}
```
**链栈(Linked Stack)**:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
ElementType data;
struct Node* next;
} StackNode;
typedef struct {
StackNode* top;
} LinkStack;
// 初始化空链栈
void initLinkStack(LinkStack* s) {
s->top = NULL;
}
// 入栈 (Push)
void pushLinkStack(LinkStack* s, ElementType e) {
StackNode* newNode = (StackNode*)malloc(sizeof(StackNode));
newNode->data = e;
newNode->next = s->top;
s->top = newNode;
}
// 出栈 (Pop)
ElementType popLinkStack(LinkStack* s) {
if (s->top == NULL) {
printf("Stack underflow.\n");
return 0; // 返回默认值,表示栈为空
} else {
StackNode* temp = s->top;
ElementType value = temp->data;
s->top = temp->next;
free(temp);
return value;
}
}
// 取栈顶元素 (Top)
ElementType getTopLinkStack(LinkStack* s) {
if (s->top == NULL) {
printf("Stack is empty.\n");
return 0; --返回默认值,表示栈为空
} else {
return s->top->data;
}
}
// 判断栈中元素个数 (IsEmpty)
int isEmptyLinkStack(LinkStack* s) {
return s->top == NULL;
}
// 置空栈 (Clear)
void clearLinkStack(LinkStack* s) {
while (s->top != NULL) {
StackNode* temp = s->top;
s->top = s->top->next;
free(temp);
}
s->top = NULL;
}
```
阅读全文