用c语言设计链栈数据类型
时间: 2023-11-19 14:55:21 浏览: 90
链栈是一种基于链表实现的栈,其数据类型可以用C语言进行设计。下面是链栈的基本结构体定义和操作函数实现:
```
typedef int ElemType;
//链栈节点定义
struct Node {
ElemType data; //数据域
struct Node* next; //指针域
};
//链栈类型定义
struct LinkStack {
struct Node* top; //栈顶指针
};
//初始化链栈
void InitLinkStack(struct LinkStack* s) {
s->top = NULL;
}
//判断链栈是否为空
bool IsEmptyLinkStack(struct LinkStack* s) {
return s->top == NULL;
}
//入栈操作
bool PushLinkStack(struct LinkStack* s, ElemType e) {
struct Node* p = (struct Node*)malloc(sizeof(struct Node));
if (p == NULL) {
return false;
}
p->data = e;
p->next = s->top;
s->top = p;
return true;
}
//出栈操作
bool PopLinkStack(struct LinkStack* s, ElemType* e) {
if (s->top == NULL) {
return false;
}
struct Node* p = s->top;
*e = p->data;
s->top = p->next;
free(p);
return true;
}
//获取栈顶元素
bool GetTopLinkStack(struct LinkStack* s, ElemType* e) {
if (s->top == NULL) {
return false;
}
*e = s->top->data;
return true;
}
//销毁链栈
void DestroyLinkStack(struct LinkStack* s) {
struct Node* p = s->top;
while (p != NULL) {
struct Node* q = p;
p = p->next;
free(q);
}
s->top = NULL;
}
```
阅读全文