栈的链表实现


    

    栈和队列,作为计算机中很重要的两种数据结构,它们的数据组织方式均可用数组和链表实现,只是存取数据时的方式有所差别。一个是遵循“先进后出”,一个是遵循“先进先出”的原则。

         


    链表实现:

  

#include<stdio.h>
#include<stdlib.h>

struct Node;
typedef struct Node *ptrtonode;
typedef ptrtonode stack;
typedef int element_type;

struct Node{
	element_type x;
	ptrtonode next;
};

int is_empty(stack s);
stack initial(void);
void make_empty(stack s);
void push(stack s,element_type x);
element_type pop(stack s);
element_type top(stack s);

void main(){
	stack sk;
	element_type a;
	sk = initial();
	push(sk, 2);
	push(sk, 4);
	push(sk, 8);
	printf("stcak is null\n?", is_empty);
	for (int i = 0; i < 3; i++){
		a = pop(sk);
		printf("pop:%d\n", a);
	}
	printf("stack is null?\n", is_empty);
}

int is_empty(stack s){
	return s->next == NULL;
}

stack initial(stack s){
	s = (ptrtonode)malloc(sizeof(struct Node));
	if (s = NULL)
		printf("out of space!\n");
	s->next = NULL;
	return s;
}

void make_empty(stack s){
	if (s = NULL)
		printf("erro");
	else
		while (s->next != NULL)
			pop(s);
}

element_type pop(stack s){
	ptrtonode top;
	element_type element;
	if (is_empty(s))
		printf("erro");
	else{
		top = s->next;
		element = top->x;
		s ->next = s->next->next;
		
		//return element;
	}
	return element;
	free(top);
}

void push(stack s, element_type x){
	ptrtonode a;
	a = (ptrtonode)malloc(sizeof(struct Node));
	if (a = NULL)
		printf("erro");
	else{
		a->x = x;
		a->next = s->next;
		s->next = a;
	}
}

element_type top(stack s){
    element_type top;
	if (s = NULL)
		printf("erro");
	else{
		top = s->next->x;
	}
	return top;
}


  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值