目录
什么是栈及其特点
栈是一种特殊的线性表,它只能在一端进行存取操作,导致其元素有先进后出的特点
栈的特点是先进后出(进栈和出栈的顺序相反,先进去的后面出来)
栈的应用场景:(1)表达式的值
(2)解决一些递归问题
(3)计算进制转换
入栈和出栈操作可以转化为结点的头插(先进行的头插的位置靠后)和删除(并且要返回第一个结点的值)
初始化栈
typedef struct Stack {
int data;
struct Stack* next;
}Stack;
//初始化(含头结点,其data表示栈内结点的个数)
Stack* initStack() {
Stack* S = (Stack*)malloc(sizeof(Stack));
S->data = 0;
S->next = NULL;
return S;
}
判断栈空
int isEmpty(Stack* S) {
if (S->data == 0 || S->next == NULL)
return 1;
else
return 0;
}
出栈
int pop(Stack* S) {
if (isEmpty(S))
return -1;
else
{
Stack* node = S->next;
int data = node->data;
S->next = node->next;
free(node);
return data;
}
}
入栈
void push(Stack* S ,int data) {
Stack* node = (Stack*)malloc(sizeof(Stack));
node->data = data;
node->next = S->next;
S->next = node;
S->data++;
}
打印
void printStack(Stack* S) {
Stack* node = S->next;
while (node) {
printf("%d->", node->data);
node = node->next;
}
printf("NULL\n");
}
用于检验上述函数效果的主函数
int main() {
Stack* S = initStack();
push(S, 1);
push(S, 2);
push(S,3 );
push(S, 4);
printStack(S);
printf("current elem = %d\n", pop(S));
printStack(S);
printf("current elem = %d\n", pop(S));
printStack(S);
return 0;
}
完整源代码
#include "headfile.h"
typedef struct Stack {
int data;
struct Stack* next;
}Stack;
//初始化(含头结点,其data表示栈内结点的个数)
Stack* initStack() {
Stack* S = (Stack*)malloc(sizeof(Stack));
S->data = 0;
S->next = NULL;
return S;
}
int isEmpty(Stack* S) {
if (S->data == 0 || S->next == NULL)
return 1;
else
return 0;
}
//出栈
int pop(Stack* S) {
if (isEmpty(S))
return -1;
else
{
Stack* node = S->next;
int data = node->data;
S->next = node->next;
free(node);
return data;
}
}
//入栈
void push(Stack* S ,int data) {
Stack* node = (Stack*)malloc(sizeof(Stack));
node->data = data;
node->next = S->next;
S->next = node;
S->data++;
}
void printStack(Stack* S) {
Stack* node = S->next;
while (node) {
printf("%d->", node->data);
node = node->next;
}
printf("NULL\n");
}
int main() {
Stack* S = initStack();
push(S, 1);
push(S, 2);
push(S,3 );
push(S, 4);
printStack(S);
printf("current elem = %d\n", pop(S));
printStack(S);
printf("current elem = %d\n", pop(S));
printStack(S);
return 0;
}