本次为大家带来的是数据结构中的链栈,链栈就是存储结构是链式的
链栈的定义
typedef struct node
{
int data;
struct node*next;
}node;
node*top;
和单链表的定义并无二致,仅仅多了一个top指针,关键在于使用者如何使用的。
链栈包括:创建链表(和单链表的头插法一样),压栈(pushstack),弹栈(popstack),打印(print)
废话不多说,看代码:
#include<stdio.h>
#include<malloc.h>
typedef struct node
{
int data;
struct node*next;
}node;
node*c_linkstack()
{
node*top,*p;
int a,n;
top=NULL;
printf(" the num:");scanf("%d",&n);
if(n>0)
{
printf("the value:");
while(n>0)
{
scanf("%d",&a);
p=(node*)malloc(sizeof(node));
p->data=a;
p->next=top;
top=p;
n--;
}
}
return top;
}
node*pushstack(node*top,int x)
{
node*p;
p=(node*)malloc(sizeof(node));
p->data=x;
p->next=top;
top=p;
return top;
}
node*popstack(node*top,int*p)
{
node*q;
if(top!=NULL)
{
q=top;
*p=top->data;
top=top->next;
free(q);
}
return top;
}
void print(node*top)
{
node*p;
p=top;
if(p!=NULL)
{
printf("the linkstack:");
while(p!=NULL)
{
printf("%4d",p->data);
p=p->next;
}
}
else puts("the linkstack is empty");
}
int main()
{
int x=0;
node*a,*b;
a=c_linkstack();
print(a);
printf("\n\ninput a linkstacking number: ");scanf("%d",&x);
a=pushstack(a,x);
print(a);
b=popstack(a,&x);
printf("\n\noutput a linkstacking number:%d\n",x);
print(b);
return 0;
}
总结
本次对数据结构链栈的编码,相对来说还是容易一些的,毕竟都是以链表为基础,所以学好基础是进一步向上扩展的第一步,温故而知新,可以为师矣。