我想在 C 中创建一个堆栈数组,我应该能够在其中保留各个堆栈及其各自的信息。我目前有以下实现,它只适用于一个堆栈。如何修改函数 push 和 pop 以实现多个堆栈,每个堆栈都使用相同的函数。 (我很容易在 Java 中做到这一点,因为我可以创建一个类,但我不知道在 C 中)
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node *next;
};
struct node *first = NULL;
void push(int x) {
struct node *newnode = malloc(sizeof(struct node));
newnode->data = x;
newnode->next = first;
first = newnode;
}
int pop() {
int temp = first->data;
first = first->next;
return temp;
}
最佳答案
pop()
函数中的代码存在内存泄漏。您应该释放您拥有 malloc 的内存。
从@Jongware 在您的问题下方的评论中获取建议。
这是 push()
和 pop()
函数的新版本。
#include <stdlib.h>
struct node {
int data;
struct node *prev;
};
void push(struct node **stack, int x) {
if (stack != NULL)
{
struct node *newnode = malloc(sizeof(struct node));
newnode->data = x;
newnode->prev = *stack;
*stack = newnode;
} else
{
// You didn't give me a valid pointer to a stack, so I'm ignoring you!
}
}
int pop(struct node **stack) {
int temp = 0; // This is the default value that is returned when there is an error.
struct node *oldnode;
if (stack != NULL)
{
if (*stack != NULL)
{
oldnode= *stack;
temp = oldnode->data;
(*stack) = oldnode->prev;
free(oldnode);
} else
{
// The stack is empty. I will just ignore you and return the default value for temp.
}
} else
{
// You didn't give me a valid pointer to a stack so I'm ignoring you and returning the default value of 0 for temp!
}
return temp;
}
下面是如何使用它们的示例:
#include <stdio.h>
int main()
{
struct node *stack1 = NULL, *stack2 = NULL;
int value;
// Push some values onto the stacks
printf("Pushing 7 and then 8 onto stack1\n");
push(&stack1, 7);
push(&stack1, 8);
printf("Pushing 3 onto stack2\n");
push(&stack2, 3);
// Pop and print both stacks
value = pop(&stack2);
printf("Popped %d from stack2\n", value);
value = pop(&stack1);
printf("Popped %d from stack1\n", value);
value = pop(&stack1);
printf("Popped %d from stack1\n", value);
return 0;
}
至于在哪里,您应该声明您的堆栈指针,这完全取决于您以及您打算如何使用它们。
阅读 C variable scope了解一些选项以及如何使用它们。
此外,在函数内部声明这些指针 时,我还必须包含一个警告。无论在哪个函数中声明指针,都必须确保在退出函数之前弹出 所有 堆栈,否则您将丢失指针并泄漏所有分配的内存.如果这不是您想要的,或者您希望指针的生命周期比函数长,那么您可以全局声明指针或传递它,确保在程序存在或丢失指针之前所有内容都从堆栈中弹出。
您可能要考虑的另一件事是当您在空堆栈上使用 pop()
时会发生什么?我为您提供的实现只是返回 0
并忽略您。您可能想要更好地处理它。
关于c - 制作多个堆栈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20849079/