第1个回答 2011-11-10
顺序栈的实现
#include <stdio.h>
#include "iostream.h"
#define STACK_INT_SIZE 100
#define STACKINCREMENT 10
typedef struct
{
int *base;
int *top;
int stacksize;
}SqStack;
int InitStack(SqStack *S)
{
S->base==(int *)malloc(STACK_INT_SIZE *sizeof(int));
if(!S->base) exit(-2);
S->top=S->base;
S->stacksize=STACK_INT_SIZE;
return 1;
}
int GetTop(SqStack S,int *e)
{
if(S.top==S.base) return 0;
e=*(S.top-1);
return 1;
}
int Push(SqStack *S,int e)
{
if(S->top-S->base>=S->stacksize)
{
S->base=(int *)realloc(S->base,(S->stacksize+STACKINCREMENT) *sizeof(int));
if(!S->base) exit(-2);
S->top=S->base+S->stacksize;
}
*S->top++=e;
return 1;
}
int Pop(SqStack *S,int e)
{
if(S->top==S->base) return 0;
e=*--S->top;
return 1;
}
main()
{
int a,b,c;
int *p1,*p2,*p3;
p1=&a;p2=&b;p3=&c;
SqStack *S;
printf("Initialize the stack.\n");
InitStack(S);
Push(S,p1);
Push(S,p2);
Push(S,p3);
GetTop(S,p3);
Pop(S,p3);
}
第2个回答 推荐于2017-09-26
#include<stdio.h>
#include<stdlib.h>
typedef struct Point
{
int data;
struct Point *next;
}P;
P* head , * tail;
int len=0;
void queue_push(P* p)
{
len++;
if(head==NULL)
{
head=tail=p;
}
else
{
tail->next=p;
tail=p;
}
}
int queue_pop()
{
if(len>=1)
{
len--;
int data;
P *h = head;
data = head->data;
head=head->next;
free(h);
return data;
}
else exit(0);
}
void queue_init()
{
head = tail=NULL;
len = 0;
}
//test
int main()
{
int n,i;
queue_init();
for(i=1;i<=10;i++)
{
P* p=(P*)malloc(sizeof(P));
p->data=i;
p->next=NULL;
queue_push(p);
}
for(i=1;i<=10;i++)printf("%d ",queue_pop());
printf("ok");
}本回答被提问者采纳