#include<stdio.h>
#include<stdlib.h>
typedef struct Node{
int data;
struct Node* next;
}Node;
typedef struct Node* PNode;//定一个Node类型的指针
typedef struct{
PNode top;//定义一个top指针
int count;//表示链表中现在有多少元素
}Stack;
void initStack(Stack* s){//这里面必须放指针类型的变量,要不然如果里面的s是一个局部变量,相当于没操作
s->top = NULL;//先将top置为NULL
s->count = 0;
}
int isEmpty(Stack* s){
return s->count == 0;
}
void push(Stack* s, int e){
PNode newNode = (PNode)malloc(sizeof(Node));
if(!newNode){
exit(0);//如果没申请空间成功就退出
}
newNode->data = e;
newNode->next = s->top;
s->top = newNode;
s->count++;
}
void pop(Stack* s){
if(isEmpty(s)){
return;
}
PNode temp = s->top;
s->top = s->top->next;
free(temp);
s->count--;
}
int get_top(Stack* s){
if(isEmpty(s)){
return -1;
}
return s->top->data;
}
int main(){
Stack s;
initStack(&s);
push(&s, 1);
push(&s, 2);
push(&s, 5);
printf("%d\n", get_top(&s));
pop(&s);
printf("%d\n", get_top(&s));
pop(&s);
printf("%d\n", get_top(&s));
pop(&s);
//上面压入1,2,5,弹出5,2,1,接下来应该就是空栈了
if(isEmpty(&s)){
printf("栈为空\n");
}else{
printf("栈不为空\n");
}
return 0;
}
链栈的构造和使用
最新推荐文章于 2024-10-07 14:53:51 发布