用C语言设计一个数据类型是键值对的堆栈数据结构
时间: 2024-03-11 11:47:44 浏览: 63
堆栈数据结构的c++实现
好的,我可以帮您解答这个问题。
首先,我们需要定义一个键值对的结构体,包含一个键和一个值:
```c
typedef struct {
int key;
int value;
} KeyValuePair;
```
然后,我们可以定义一个堆栈结构体,包含一个指向键值对的数组的指针,一个栈顶指针和一个堆栈的最大容量:
```c
typedef struct {
KeyValuePair* items;
int top;
int maxSize;
} Stack;
```
接下来,我们可以实现一些堆栈的基本操作,如初始化、入栈、出栈、获取栈顶元素等:
```c
void initStack(Stack* stack, int maxSize) {
stack->items = (KeyValuePair*)malloc(maxSize * sizeof(KeyValuePair));
stack->top = -1;
stack->maxSize = maxSize;
}
void push(Stack* stack, KeyValuePair item) {
if (stack->top == stack->maxSize - 1) {
printf("Error: Stack is full\n");
return;
}
stack->top++;
stack->items[stack->top] = item;
}
KeyValuePair pop(Stack* stack) {
if (stack->top == -1) {
printf("Error: Stack is empty\n");
KeyValuePair empty = { -1, -1 };
return empty;
}
KeyValuePair item = stack->items[stack->top];
stack->top--;
return item;
}
KeyValuePair top(Stack* stack) {
if (stack->top == -1) {
printf("Error: Stack is empty\n");
KeyValuePair empty = { -1, -1 };
return empty;
}
return stack->items[stack->top];
}
```
最后,我们可以在主函数中测试这个堆栈数据结构:
```c
int main() {
Stack stack;
initStack(&stack, 10);
KeyValuePair item1 = { 1, 100 };
KeyValuePair item2 = { 2, 200 };
push(&stack, item1);
push(&stack, item2);
KeyValuePair topItem = top(&stack);
printf("Top item: (%d, %d)\n", topItem.key, topItem.value);
KeyValuePair popItem = pop(&stack);
printf("Pop item: (%d, %d)\n", popItem.key, popItem.value);
topItem = top(&stack);
printf("Top item: (%d, %d)\n", topItem.key, topItem.value);
popItem = pop(&stack);
printf("Pop item: (%d, %d)\n", popItem.key, popItem.value);
popItem = pop(&stack);
printf("Pop item: (%d, %d)\n", popItem.key, popItem.value);
return 0;
}
```
输出结果为:
```
Top item: (2, 200)
Pop item: (2, 200)
Top item: (1, 100)
Pop item: (1, 100)
Error: Stack is empty
Pop item: (-1, -1)
```
希望这个例子能够帮助您更好地理解堆栈数据结构的实现。
阅读全文