某一线性数据结构的数据集中的元素数据为不同城市的省会及其位置,数据元素类型定义为: typedef struct{ int city_id; double x; double y; double z; } ElemType; 通过创建链栈记录数据集,并实现销毁、入栈、出栈和获取栈顶元素的C语言代码实现。
时间: 2023-06-07 10:12:04 浏览: 81
好的,这是C语言实现某一线性数据结构的链栈操作的代码:
#include <stdio.h>
#include <stdlib.h>
typedef struct stack_node {
ElemType data;
struct stack_node *next;
} StackNode, *LinkStack;
// 初始化链栈
LinkStack InitStack() {
LinkStack top = (LinkStack)malloc(sizeof(StackNode));
top->next = NULL;
return top;
}
// 入栈操作
void Push(LinkStack top, ElemType data) {
StackNode *node = (StackNode*)malloc(sizeof(StackNode));
node->data = data;
node->next = top->next;
top->next = node;
}
// 出栈操作
ElemType Pop(LinkStack top) {
if (top->next == NULL) {
printf("The stack is empty!\n");
return;
}
StackNode *node = top->next;
top->next = node->next;
ElemType data = node->data;
free(node);
return data;
}
// 获取栈顶元素
ElemType GetTop(LinkStack top) {
if (top->next == NULL) {
printf("The stack is empty!\n");
return;
}
return top->next->data;
}
// 销毁链栈
void DestroyStack(LinkStack top) {
StackNode *p = top->next;
while (p != NULL) {
top->next = p->next;
free(p);
p = top->next;
}
free(top);
}
// 测试代码
int main() {
LinkStack top = InitStack();
ElemType e1 = {1, 1.0, 2.0, 3.0};
Push(top, e1);
ElemType e2 = {2, 4.0, 5.0, 6.0};
Push(top, e2);
ElemType e3 = {3, 7.0, 8.0, 9.0};
Push(top, e3);
printf("栈顶元素: city_id=%d, x=%lf, y=%lf, z=%lf\n", GetTop(top).city_id, GetTop(top).x, GetTop(top).y, GetTop(top).z);
ElemType e4 = Pop(top);
printf("出栈元素: city_id=%d, x=%lf, y=%lf, z=%lf\n", e4.city_id, e4.x, e4.y, e4.z);
DestroyStack(top);
return 0;
}
阅读全文