链栈的构造和使用

#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;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值