基本栈操作
#include <stdio.h>
#include <stdlib.h>
#define EMPTY 1
#define NONEMPTY 0
typedef struct Node
{
int data;
struct Node *next;
} Node;
Node *initStack()
{
Node *Stack = (Node *)malloc(sizeof(Node));
if (Stack == NULL)
{
printf("malloc Stack error!\n");
}
Stack->data = 0;
Stack->next = NULL;
return Stack;
}
int isEmpty(Node *Stack)
{
if (Stack->data == 0 || Stack->next == NULL)
{
return EMPTY;
}
else
{
return NONEMPTY;
}
}
int getTop(Node *Stack) // 获取栈顶元素
{
if (isEmpty(Stack) == EMPTY)
{
return -1;
}
else
{
return Stack->next->data;
}
}
int pop(Node *Stack) // 出栈
{
if (isEmpty(Stack) == EMPTY)
{
return -1;
}
else
{
Node *node = Stack->next;
int data = node->data;
Stack->next = node->next;
free(node);
Stack->data--;
return data;
}
}
void push(Node *Stack, int data) // 压栈
{
Node *newNode = (Node *)malloc(sizeof(Node));
if (newNode == NULL)
{
printf("malloc newNode error!\n");
}
newNode->data = data;
newNode->next = Stack->next;
Stack->next = newNode;
printf("%d 入栈\n", data);
Stack->data++;
}
void printStack(Node *Stack)
{
printf("遍历栈 > ");
Node *current = Stack->next;
while (current != NULL)
{
printf("%d -> ", current->data);
current = current->next;
}
printf("over\n");
}
int main(int argc, char const *argv[])
{
Node *Stack = initStack();
for (int i = 0; i <= 10; i++)
{
push(Stack, i);
}
printf("----------------------------------------------------------\n");
printStack(Stack);
printf("----------------------------------------------------------\n");
printf("现在站内存在 %d 个元素\n", Stack->data);
printf("----------------------------------------------------------\n");
for (int i = 0; i <= 10; i++)
{
int data = pop(Stack);
printf("当前 %d 出栈\n", data);
}
printf("----------------------------------------------------------\n");
printf("现在站内还剩 %d 个元素\n", Stack->data);
printf("----------------------------------------------------------\n");
printStack(Stack);
return 0;
}
运行结果如下:
0 入栈
1 入栈
2 入栈
3 入栈
4 入栈
5 入栈
6 入栈
7 入栈
8 入栈
9 入栈
10 入栈
----------------------------------------------------------
遍历栈 > 10 -> 9 -> 8 -> 7 -> 6 -> 5 -> 4 -> 3 -> 2 -> 1 -> 0 -> over
----------------------------------------------------------
现在站内存在 11 个元素
----------------------------------------------------------
当前 10 出栈
当前 9 出栈
当前 8 出栈
当前 7 出栈
当前 6 出栈
当前 5 出栈
当前 4 出栈
当前 3 出栈
当前 2 出栈
当前 1 出栈
当前 0 出栈
----------------------------------------------------------
现在站内还剩 0 个元素
----------------------------------------------------------
遍历栈 > over