用鏈表實現棧結構
棧結構簡單介紹
棧結構通俗來說是元素先進后出,就像一個水瓶,依次往里裝東西,最先裝進去的被壓在下面,要出來時得先拿走上面壓着的東西,
才能取出來。所以說棧是運算受限的線性表,因為棧只允許在表的一端進行增刪。
實現
本文使用單鏈表來實現棧結構。先構建一個帶head 節點的鏈表,每次添加元素(進棧),
使新節點->next指向head->next,使head節點指向新節點。數組結構的實現見下一篇。
具體實現代碼如下
//定義節點
typedef struct data{
int value;
struct data *next;
}node;
//初始化node
node *newData(int age){
//動態分配內存
node *p = (node *)malloc(sizeof(node));
p->value = age;
return p;
}
//建立空棧
node *newStack(){
//建立頭結點
node *head = newData(-1);
//頭結點的下一個節點置空
head->next = NULL;
return head;
}
//add element in first 進棧
void pash(node *head, node *p){
//將元素添加到表頭,以實現棧結構
p->next = head->next;
head->next = p;
}
//出棧
void pop(node *head){
if(isEmpty(head)){
printf("the stack is empty");
exit(1);
}
node *p = head->next;
head->next = head->next->next;
free(p);
}
//取棧頂
node *getTop(node *head){
if(isEmpty(head)){
return NULL;
}
return head->next;
}
//判棧空
int isEmpty(node *head){
if(head->next == NULL){
return 1;
}
return 0;
}
void test(){
node *head = newStack();
pash(head,newData(1));
pash(head,newData(2));
pash(head,newData(3));
pash(head,newData(4));
pash(head,newData(5));
while(!isEmpty(head)){
printf("%d\n",getTop(head)->value);
pop(head);
}
}