用c语言实现链栈 (带头结点)

#include 
#include 
#include 
#include 
#include 
using namespace std;
typedef struct Node
{
   int element;
   struct Node* next;
}Node;
///创建空的栈
Node *creatstack()
{
  Node *s = (Node *)malloc(sizeof(Node));
  if(!s) return NULL;
  s ->next = NULL;
  return s;
}
///创建空的节点
Node *creatNode(int item)
{
	Node *tmp = (Node*)malloc(sizeof(Node));
	if(!tmp) return NULL;
	tmp->next = NULL;
	tmp->element = item;
	return tmp;
}
///插入节点,入栈,链表的头插入节点元素
void push(Node *s,int item)
{
	Node *tmp = creatNode(item);
    if(!tmp) printf("无法申请内存");
	else
	{
		tmp->next = s->next;
		s->next = tmp;
	}
}
///取出栈顶元素
int top(Node* s)
{
	return s->next->element;
}
///出栈
void pop(Node* s)
{
	Node *tmp = s->next;
	s->next = s->next->next;
	free(tmp);
}
///打印栈中元素,越早进去,越晚出来
void print(Node* s)
{
	Node *p = s->next;
	while(p)
	{
		printf("%d ",p->element);
		p = p->next;
	}
	printf("\n");
}
///求栈中元素的多少
int sizestack(Node *s)
{
	Node *p = s->next;
    int cnt = 0;
	while(p)
	{
		cnt ++;
		p = p->next;
	}
	return cnt;
}
///检验栈是否为空
bool isempty(Node* s)
{
	return s->next==NULL;
}

int main()
{
   Node *stack = creatstack();
   push(stack,5);
   //push(stack,6);
   //push(stack,7);
   //push(stack,8);
   //push(stack,9);
   //push(stack,10);
   print(stack);
   printf("%d\n",top(stack));
   pop(stack);
   print(stack);
   printf("%d\n",sizestack(stack));
   if(isempty(stack)) printf("emtpy!\n");
   return 0;
}

你可能感兴趣的:(优先队列,队列,栈,堆)