基于链表的栈实现(C)
typedef struct Node { int data; struct Node *next; } Node; typedef struct { Node *top; } LinkedListStack;
bool push(LinkedListStack *stack, int item) {
Node *newNode = (Node *)malloc(sizeof(Node));
if (!newNode) {
// Memory allocation failed
return false;
}
newNode->data = item;
newNode->next = stack->top;
stack->top = newNode;
return true;
}
bool pop(LinkedListStack *stack, int *item) {
if (isEmpty(stack)) {
// Stack is empty
return false;
}
Node *temp = stack->top;
*item = temp->data;
stack->top = temp->next;
free(temp);
return true;
}
push(&stack, 1);
push(&stack, 2);
push(&stack, 3);
printf("Peek: %d\n", peek(&stack)); // Output: 3
int poppedItem;
pop(&stack, &poppedItem);
printf("Popped: %d\n", poppedItem); // Output: 3
这两个示例代码分别展示了如何使用C语言实现基于数组和链表的栈。基于数组的栈通过数组来存储元素,并使用一个变量来跟踪栈顶的位置。基于链表的栈则使用链表节点来存储元素,并将栈顶作为链表的头部。两个实现都包含了初始化栈、判断栈是否为