1. 程式人生 > >用c語言實現鏈棧 (帶頭結點)

用c語言實現鏈棧 (帶頭結點)

#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <stdlib.h>
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;
}