ITfeng

 

数据结构-栈实现(数组和队列)

链表实现栈

#include<stdio.h>
#include<stdlib.h>
typedef struct list
{
int data;
struct list *next;
}List;
typedef struct stack
{
List*top;
}Stack;
void init_stack(Stack*s)
{
s->top=NULL;
}
void push_stack(Stack *s,int data)
{
List *newnode=(List*)malloc(sizeof(List));
newnode->data=data;
newnode->next=s->top;
s->top=newnode;
}
int pop_stack(Stack *s)
{ int temp;
List*p;
if(s->top==NULL)
{
printf("stack is empty,can't pop stack\n");
return -1;
}
temp=s->top->data;
p=s->top;
s->top=s->top->next;
free(p);
return temp;
}
int main()
{ int i=0;
Stack *s=(Stack*)malloc(sizeof(Stack));
init_stack(s);
for(i=0;i<10;i++)
push_stack(s,i);
for(i=0;i<10;i++)
printf("%d\n",pop_stack(s));
}

数组实现栈

#include<stdio.h>
#include<stdlib.h>
#define N 100
typedef struct stack
{
int store[N];
int top;
}Stack;
void init_stack(Stack *s)
{
s->top=-1;
}
void push_stack(Stack*s,int data)
{
if(s->top==N-1)
printf("stack is full now\n");
s->store[++s->top]=data;
}
int pop_stack(Stack*s)
{ int temp;
if(s->top==-1)
printf("stack is empty\n");
temp=s->store[s->top--];
return temp;
}
int main()
{
int i=0;
Stack *s=(Stack*)malloc(sizeof(Stack));
init_stack(s);
for(i=0;i<10;i++)
push_stack(s,i);
for(i=0;i<10;i++)
printf("%d\n",pop_stack(s));
}

posted on 2012-04-18 21:24  ITfeng  阅读(204)  评论(0编辑  收藏  举报

导航