用链表实现栈结构
栈结构简单介绍
栈结构通俗来说是元素先进后出,就像一个水瓶,依次往里装东西,最先装进去的被压在下面,要出来时得先拿走上面压着的东西,
才能取出来。所以说栈是运算受限的线性表,因为栈只允许在表的一端进行增删。
实现
本文使用单链表来实现栈结构。先构建一个带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);
}
}