链栈简单操作

 

/*设置一个静态变量记链表值的个数
入栈是头插法
*/
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
static int count=0;
typedef struct node
{
int data;
struct node *next;
}stacknode,*linkstack;
/*typedef struct stack
{
struct stack pop;
struct stack bottom;
}stack,*pstack;
*/
void init (linkstack l)
{
l=(linkstack)malloc(sizeof(stacknode));
if(l==NULL)
{
printf("分配内存失败");
exit(-1);
}
l->next=NULL;

}

int empty(linkstack l)
{
if(l->next==NULL)
{
printf("链栈为空\n");
return 1;
}
else
{
printf("链栈不为空\n");
printf("\n");
return 0;
}
}
int push(linkstack l,int n)
{
linkstack p,q;
p=(linkstack)malloc(sizeof(stacknode));
q=l;
if(p==NULL)
{
printf("分配内存失败");
exit(-1);
}
else
{
p->data=n;
p->next=q->next;
q->next=p;
count++;
return 1;
}

}

int pop(linkstack l)
{ int num;
linkstack p,q;
if(empty(l))
{
printf("栈为空");
return 0;
}
p=l->next;
num=p->data;
l->next=p->next;
free(p);
count--;
return 1;
}


void gettop(linkstack l)
{
printf("输出链表栈顶的值%d",l->next->data);
printf("\n");


}
void tra(linkstack l)
{
linkstack p;
int j=0;
p=l->next;
for(j=0;j<count;j++)
{
printf("%d ",p->data);
p=p->next;
}
printf("\n");
}


int main()
{
linkstack l,p;
l=(linkstack)malloc(sizeof(stacknode));
init(l);
printf("入栈6个数\n");
push(l,1);
push(l,2);
push(l,3);
push(l,4);
push(l,5);
push(l,6);
tra(l);
gettop(l);

pop(l);
printf("出栈后\n");
gettop(l);
printf("\n");
printf("\n");
printf("\n");
printf("%d ",count);
return 0;
}

 

posted @ 2016-09-13 04:34  mykonons  阅读(159)  评论(0编辑  收藏  举报