Posted on 2012-09-17 15:41
hoshelly 閱讀(304)
評論(0) 編輯 收藏 引用 所屬分類:
DS && Algorithm
#include<stdio.h>
#include<stdlib.h>
typedef struct STACKnode* link; //堆棧的鏈表實現
struct STACKnode
{
int item;
link next;
};
static link head;
link NEW(int item,link next)
{
link x=(link)malloc(sizeof(STACKnode));
x->item = item; //將新建立的結點添加到鏈表頭
x->next = next; //此時head指向新建立的結點,此結點的next結點,即為原先是頭結點的結點(舊頭結點)
return x; //函數返回新建立的頭結點,此結點總是位于棧頂
}
void STACKinit()
{
head = NULL;
}
int STACKempty() //置空棧
{
return head == NULL;
}
void STACKpush(int item)
{
head = NEW(item,head);
}
int STACKpop()
{
int item = head->item; //將頭結點上的值取出
link t = head->next;
free(head); //釋放此頭結點內存
head = t; //head指向新的頭結點t
return item; //返回舊的頭結點的值
}
int main()
{
int i;
STACKinit();
for(i=1;i<=10;i++)
STACKpush(i);
for(i=1;i<=10;i++)
printf("%d ",STACKpop());
printf("\n");
return 0;
}