一.定义结构体
typedef struct LNode {
int data;
struct LNode* top;
}LNode, * List;
二.初始化栈
List init() {
LNode* T = malloc(sizeof(LNode));
T->top = NULL;
return T;
}
三.入栈
void push(LNode* T, int e) {
LNode* p = malloc(sizeof(LNode));
p->data = e;
p->top = T->top;
T->top = p;
}
四.出栈
bool pop(LNode* T, int* e) {
//栈空
if (T->top == NULL) {
return false;
}
LNode* p = T->top;
*e = p->data;
T->top = p->top;
free(p);
return true;
}
五.栈空
//判断栈空
bool Lempty(LNode* T)
{
if (T->top == NULL)
return false;
else
{
return true;
}
}
六.栈的遍历
//输出
void print(LNode* T) {
printf("(top)\n");
LNode* p = T->top;
while (p != NULL) {
printf("%d ", p->data);
p = p->top;
}
printf("\n");
}
完整代码
typedef struct LNode {
int data;
struct LNode* top;
}LNode, * List;
List init() {
LNode* T = malloc(sizeof(LNode));
T->top = NULL;
return T;
}
//输出
void print(LNode* T) {
printf("(top)\n");
LNode* p = T->top;
while (p != NULL) {
printf("%d ", p->data);
p = p->top;
}
printf("\n");
}
//入栈
void push(LNode* T, int e) {
LNode* p = malloc(sizeof(LNode));
p->data = e;
p->top = T->top;
T->top = p;
}
//出栈
bool pop(LNode* T, int* e) {
//栈空
if (T->top == NULL) {
return false;
}
LNode* p = T->top;
*e = p->data;
T->top = p->top;
free(p);
return true;
}
//判断栈空
bool Lempty(LNode* T)
{
if (T->top == NULL)
return false;
else
{
return true;
}
}
int main() {
LNode* T = init();
int n, i, e;
scanf("%d", &n);
for (i = 0; i < n; i++) {
scanf("%d", &e);
push(T, e);
}
print(T);
}