链栈

本文介绍了使用C语言实现的基本栈操作,包括初始化、压栈、弹栈、获取栈顶元素和栈长度的方法。
#include <stdio.h>
#include <stdlib.h>

struct lstack{
	char data;
	struct lstack * next;
};

struct lstack * init(){
	struct lstack * top;
	top = (struct lstack *)malloc(sizeof(struct lstack));
	top->data='0';
	top->next=NULL;
	return top;
}

int push(struct lstack * top,char data){
	struct lstack * p;
	p=(struct lstack *)malloc(sizeof(struct lstack));
	p->data=data;
	p->next=top->next;
	top->next=p;
	printf("%c入栈\n",data);
	return 0;
}

int pop(struct lstack * top){
	struct lstack * p;
	if(top->next==NULL){
		printf("栈空!删除失败!\n");
	}
	else{
		p = top->next;
		top->next=p->next;
		printf("%c出栈\n",p->data);
		free(p);
	}
	return 0;
}

int getTop(struct lstack * top){
	struct lstack * p;
	if(top->next==NULL){
		printf("栈空!无栈顶元素!\n");
	}
	else{
		p=top->next;
		printf("当前栈顶元素:%c\n",p->data);
	}
	return 0;
}

int getLength(struct lstack * top){
	struct lstack * p;
	p=top->next;
	int len=0;
	while(p!=NULL){
		len++;
		p=p->next;
	}
	printf("当前栈的长度为:%d\n",len);
	return 0;
}

void display(struct lstack * top){
	struct lstack * p;
	if(top->next==NULL){
		printf("栈空!无元素!\n");
	}
	else{
		p=top->next;
		printf("打印当前栈:");
		while(p!=NULL){
			printf("%c ",p->data);
			p=p->next;
		}
		printf("\n");
	}
}

int main(){
	struct lstack * s;
	s=init();
	push(s,'a');
	push(s,'b');
	push(s,'c');
	getLength(s);
	display(s);
	pop(s);
	pop(s);
	pop(s);
	pop(s);
	getLength(s);
	display(s);
	getTop(s); 
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值