【发布时间】:2025-12-31 07:50:09
【问题描述】:
我已经实现了一个带有指针的堆栈,它的工作方式也像假设的那样。现在,我需要它推送到堆栈,而不是推送副本。例如,如果我将“2”压入堆栈,再压入另一个“2”仍然会导致堆栈中只有一个“2”,因为它已经存在。
以下是我尝试创建新推送功能的方法。我知道我想遍历堆栈并检查我要添加的元素,但我想我做错了吗?谁能帮帮我?
typedef struct Node {
void *content;
struct Node *next;
} Node;
typedef struct Stack {
Node *head;
int count;
} Stack;
void push(Stack *stack, void *newElem) {
Node *newNode = (Node*) malloc(sizeof(Node));
if (stack->count > 0) {
int i;
for (i = 0, newNode = stack->head; i < stack->count; i++, newNode =
newNode->next) {
if (newNode->content == newElem) return;
}
} else {
newNode->next = stack->head;
newNode->content = newElem;
stack->head = newNode;
stack->count++;
}
}
【问题讨论】:
-
请注意,在您知道需要添加项目之前,您不应执行
malloc()。如果您推送的项目已经存在,您将泄漏内存。您不知道如何比较两个节点的值(内容);content指向的空间有多大,什么是合适的比较器函数。
标签: c linked-list stack duplicates push