栈是动态变化的结构,顺序栈在一定的程度上可以满足这种动态结构所要求的动态操作,但是以具有固定长度的数组来存储这种动态变化的数据结构是有局限性的。为了克服顺序栈的这个缺点,可以将栈用链式存储结构表示,这种存储结构的栈称为链栈。链栈即采用链表作为存储结构实现的链栈,在一个链栈中,为了方便进行插入和删除操作,一般指定链表头为栈顶,链尾为栈底。
#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
int data;
struct node*next;
}NODE,* stacknode;
stacknode stack_creat()
{
stacknode top;
stacknode p;
int a,n;
top = NULL;
printf("Please input the number of element\n");
scanf("%d",&n);
if(n > 0)
{
printf("please input the %dst element of stack\n",n);
while(n > 0)
{
printf("please input the element\n");
scanf("%d",&a);
p = (stacknode)malloc(sizeof(NODE));
p->data = a;
p->next = top;
top = p;
n--;
}
}
return top;
}
stacknode stack_push(stacknode top,int x)
{
stacknode p;
p = (stacknode)malloc(sizeof(NODE));
p->data = x;
p->next = top;
top = p;
return(top);
}
stacknode stack_pop(stacknode top,int x)
{
stacknode q;
if(top != NULL)
{
q = top;
x = top->data;
top = top->next;
free(q);
}
return(top);
}
void print(stacknode top)
{
stacknode p;
p = top;
if(p != NULL)
{
printf("output the stack\n");
while(p != NULL)
{
printf("%-3d",p->data);
p = p->next;
}
}
else
{
printf("the stack is empty\n");
}
}
int main()
{
int y = 0;
stacknode L;
L = stack_creat();
print(L);
putchar('\n');
putchar('\n');
printf("******the operation of pushstack\n****");
printf("please input a element of the pushstack\n");
scanf("%d",&y);
L = stack_push(L,y);
print(L);
L = stack_pop(L,y);
putchar('\n');
putchar('\n');
printf("******the operation of popstack****\n");
printf("exput the element :%d\n",y);
print(L);
}