码迷,mamicode.com
首页 > 其他好文 > 详细

栈的链表实现

时间:2015-08-13 18:12:08      阅读:116      评论:0      收藏:0      [点我收藏+]

标签:

    

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

         


    链表实现:

  

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


  

版权声明:本文为博主原创文章,未经博主允许不得转载。

栈的链表实现

标签:

原文地址:http://blog.csdn.net/sinat_21595363/article/details/47612691

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!