栈(Stack):是只允许在一端进行插入或删除的线性表。首先栈是一种线性表,但限定这种线性表只能在某一端进行插入和删除操作。

栈顶(Top):线性表允许进行插入删除的那一端。
栈底(Bottom):固定的,不允许进行插入和删除的另一端。
空栈:不含任何元素的空表。
栈又称为后进先出(Last In First Out)的线性表,简称LIFO结构
栈的常见基本操作
InitStack(&S):初始化一个空栈S。
StackEmpty(&S):判断一个栈是否为空,若栈为空则返回true,否则返回false。
Push(&S, x):进栈(栈的插入操作),若栈S未满,则将x加入使之成为新栈顶。
Pop(&S):出栈(栈的删除操作),若栈S非空,则弹出栈顶元素,并用x返回。
GetTop(S, &x):读栈顶元素,若栈S非空,则用x返回栈顶元素。
DestroyStack(&S):栈销毁,并释放S占用的存储空间(“&”表示引用调用)。
栈源码
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* next;
}Node;
Node* initStack() {
Node* L = (Node *)malloc(sizeof(Node));
if (!L) return NULL;
L->data = 0;
L->next = NULL;
return L;
}
void push(Node *L,int data) {
Node* last = L;
Node* new_node = initStack();
new_node->data = data;
while (last->next != NULL) {
last = last->next;
}
last->next = new_node;
}
int isEmpty(Node* L) {
if (L->data == 0 && L->next == NULL) {
return 1;
}
else {
return 0;
}
}
void pop(Node *L) {
if (isEmpty(L)) {
return;
} else {
Node* last = L;
Node* pre = L;
while (last->next != NULL) {
pre = last;
last = last->next;
}
free(last->next);
pre->next = NULL;
}
}
void printStack(Node *L) {
if (isEmpty(L)) {
return;
} else {
Node* last = L->next;
while (last) {
printf("last->data = %d \r\n",last->data);
last = last->next;
}
}
}
int main() {
Node* node = initStack();
push(node, 1);
push(node, 2);
push(node, 3);
pop(node);
pop(node);
printStack(node);
return 0;
}
2771

被折叠的 条评论
为什么被折叠?



