用c語言寫棧的壓入與輸出
在寫函式程式的時候,一般而言需要注意的是程式設計的規範的問題,但是自己感覺在這方面做的還很不夠,因此,將以下規範寫在自己的部落格裡,希望自己和讀者能夠重視,並將此規範運用到自己的程式當中。
類、函式和每局型別的名稱形如:LikeThis,即單詞的首字母大寫;變數名形如:likeThis,即第一個單詞的首字母小寫,第二個單詞的首字母大寫,私有成員變數名形如:likeThis_,巨集名形如:LIKE_THIS
#include<stdio.h>
#include <stdlib.h>
#include <assert.h>
struct link
{
int data ;
struct link* next;
};
struct stack
{
struct link* head;
int size;
};
void stackinit(struct stack* stack1)
{
stack1->head=NULL;
stack1->size=0;
}
void stackpush(struct stack* stack1,const int data)
{
struct link* node;
node=( struct link*)malloc(sizeof(struct link));
assert(node!=NULL);
node->data=data;
node->next=stack1->head;
stack1->head=node;
++stack1->size;
}
int stackempty(struct stack *stack1)
{
return (stack1->size==0);
}
int stackpop(struct stack*stack1, int* data )
{
if (stackempty(stack1))
{
return 0;
}
struct link* tep;
*data=stack1->head->data;
tep=stack1->head;
stack1->head=stack1->head->next;
free(tep);
--stack1->size;
return 1;
}
void stackcleanup(struct stack * stack1)
{
struct link* tmp;
while(stack1->head)
{
tmp=stack1->head;
stack1->head=stack1->head->next;
free(tmp);
}
stack1->size=0;
}
int main()
{
struct stack zhan;
stackinit(&zhan);
int i;
for (i=0;i<5;i++)
{
stackpush(&zhan,i);
}
while (!stackempty(&zhan))
{
stackpop(&zhan,&i);
printf("%d",i);
printf("\n");
}
printf("\n");
return 0;
}
執行的結果是: