编写一个程序,实现链栈的各种基本运算(假设链栈的元素类型elemtype为char),并在此
时间: 2023-12-14 11:00:30 浏览: 139
链栈是一种基于链表实现的栈结构,它具有入栈、出栈、判断栈空、获取栈顶元素等基本操作。下面我将用C语言来编写一个链栈的基本运算程序。
首先,我们需要定义链栈节点的数据结构,包括数据域和指针域:
```c
typedef struct Node {
char data;
struct Node* next;
} Node;
typedef struct {
Node* top;
} LinkStack;
```
接着,我们可以实现链栈的入栈操作:
```c
void push(LinkStack* stack, char elem) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = elem;
newNode->next = stack->top;
stack->top = newNode;
}
```
然后是出栈操作:
```c
char pop(LinkStack* stack) {
if (isEmpty(stack)) {
printf("Error: stack is empty\n");
return '\0';
}
char elem = stack->top->data;
Node* temp = stack->top;
stack->top = stack->top->next;
free(temp);
return elem;
}
```
判断栈空操作:
```c
int isEmpty(LinkStack* stack) {
return stack->top == NULL;
}
```
获取栈顶元素操作:
```c
char getTop(LinkStack* stack) {
if (isEmpty(stack)) {
printf("Error: stack is empty\n");
return '\0';
}
return stack->top->data;
}
```
最后,我们可以在main函数中测试这些操作:
```c
int main() {
LinkStack stack;
stack.top = NULL;
push(&stack, 'a');
push(&stack, 'b');
push(&stack, 'c');
printf("Top element: %c\n", getTop(&stack));
printf("Pop element: %c\n", pop(&stack));
printf("Pop element: %c\n", pop(&stack));
printf("Pop element: %c\n", pop(&stack));
printf("Is stack empty? %d\n", isEmpty(&stack));
return 0;
}
```
通过这样的程序,我们可以实现链栈的各种基本运算,包括入栈、出栈、判断栈空、获取栈顶元素等操作。并且在main函数中测试这些操作的正确性。
阅读全文
相关推荐


















