链栈的实现c语言
作者:
._4260
,
2025-04-24 20:14:24
· 河北
,
所有人可见
,
阅读 1
链栈的实现c语言
#include<iostream>
using namespace std;
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
typedef struct StackNode {
int data;
struct StackNode* next;
} StackNode;
StackNode* initStack() {
StackNode* head = (StackNode*)malloc(sizeof(StackNode));
if (!head) return NULL;
head->next = NULL;
return head;
}
bool isEmpty(StackNode* head) {
return head->next == NULL;
}
bool push(StackNode* head, int x) {
StackNode* newNode = (StackNode*)malloc(sizeof(StackNode));
if (!newNode) return false;
newNode->data = x;
newNode->next = head->next;
head->next = newNode;
return true;
}
bool pop(StackNode* head) {
if (isEmpty(head)) return false;
StackNode* temp = head->next;
head->next = temp->next;
free(temp);
return true;
}
bool getTop(StackNode* head, int* x) {
if (isEmpty(head)) return false;
*x = head->next->data;
return true;
}
void destroyStack(StackNode* head) {
StackNode* curr = head;
while (curr) {
StackNode* temp = curr;
curr = curr->next;
free(temp);
}
}
void printStack(StackNode* head) {
if (isEmpty(head)) {
printf("Stack is empty\n");
return;
}
printf("Stack top -> ");
StackNode* p = head->next;
while (p) {
printf("%d -> ", p->data);
p = p->next;
}
printf("NULL\n");
}
int main() {
StackNode* stack = initStack();
if (!stack) {
printf("Init stack failed!\n");
return 1;
}
push(stack, 10);
push(stack, 20);
push(stack, 30);
printStack(stack);
int top;
if (getTop(stack, &top)) {
printf("Top element: %d\n", top);
}
pop(stack);
printStack(stack);
pop(stack);
pop(stack);
if (!pop(stack)) {
printf("Pop failed: stack is empty\n");
}
destroyStack(stack);
return 0;
}