//数组实现栈
#include <stdio.h>
#define STACK_SIZE 50
typedef struct SeqStack
{
int data[STACK_SIZE];
int top;
}stack;
void InitStack()
{
s->top = -1;
}
int IsFull(stack *s)
{
return (s->top == STACK_SIZE - 1);
}
int IsEmpty(stack *s)
{
return (s->top == -1);
}
void Push(stack *s,int n)
{
if(IsFull(s))
{
printf("Stack is full!\n");
return;
}
s->top++;
s->data[s->top] = n;
}
int Pop(stack *s)
{
if(IsEmpty(s))
{
printf("Stack is empty!\n");
return -1;
}
return s->data[s->top--];
}
void main()
{
stack *s = (stack *)malloc(sizeof(stack));
if(s == NULL)
{
printf("Malloc failed!");
exit(-1);
}
InitStack(s);
int i;
for(i=0;i<10;i++)
{
Push(s,i);
}
while(!IsEmpty(s))
{
int data = Pop(s);
printf("%d->",data);
}
}
//链表实现栈
#include<stdio.h>
typedef struct LinkListNode
{
int data;
struct LinkListNode *next;
}node;
typedef struct LinkStack
{
node *top;
}stack;
void init_stack(stack *s)
{
s->top = NULL;
}
void push_stack(stack *s,int data)
{
node *newnode=(node *)malloc(sizeof(node));
newnode->data=data;
newnode->next=s->top;
s->top=newnode;
}
int pop_stack(stack *s)
{
int temp;
node *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()
{
stack *s=(Stack*)malloc(sizeof(stack));
init_stack(s);
int i;
for(i=0;i<10;i++)
{
push_stack(s,i);
}
for(i=0;i<10;i++)
{
printf("%d\n",pop_stack(s));
}
}
数组、链表实现栈(C语言版)
最新推荐文章于 2019-09-20 22:22:00 发布