链栈(带头结点,头节点数据域为栈中元素数量)
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* next;
}Node;
Node* initStack() {
Node* stack = (Node*)malloc(sizeof(Node));
stack->data = 0;
stack->next = NULL;
return stack;
}
void push(Node* stack, int data) {
Node* n = (Node*)malloc(sizeof(Node));
n->data = data;
n->next = stack->next;
stack->next = n;
stack->data++;
}
int pop(Node* stack) {
if (stack->data == 0) {
return 0;
}
else {
Node* temp = stack->next;
int data = temp->data;
stack->next = temp->next;
free(temp);
stack->data--;
return data;
}
}
void printStack(Node* stack) {
Node* temp = stack->next;
while (temp) {
printf("%d ", temp->data);
printf("\n");
temp = temp->next;
}
printf("\n");
}
void test() {
Node* stack = initStack();
push(stack, 10);
push(stack, 20);
push(stack, 30);
push(stack, 40);
push(stack, 50);
push(stack, 60);
printStack(stack);
pop(stack);
printStack(stack);
pop(stack);
printStack(stack);
}
int main() {
test();
return 0;
}