栈的基本操作的实现(c语言),高手速来!!

Python07

栈的基本操作的实现(c语言),高手速来!!,第1张

/*程序错误太多*/ #include"stdio.h"

#include"stdlib.h"

#include"time.h"

#include"malloc.h"

#define

STACK_INIT_SIZE

10

//栈容量 typedef

struct

SqStack

{

int

top

//栈顶当前指针

int

*base

//栈空间数组

}SqStackvoid

InitStack(SqStack

&S)

//构造空栈S

int

Push(SqStack

&S,int

e)

//入栈(栈地址,入栈数据

返回0对,-1错

int

Pop(SqStack

&S)

//出栈

(栈地址)返回栈顶数据

int

StackLength(SqStack

S)

//返回站的元素个数,即求栈长

void

Print_S(SqStack

S)

//显示栈内数据 int

main()

{

SqStack

S

int

i=0

int

a,e

InitStack(S)

srand((unsigned)time(NULL))

//srand((unsigned)time(NULL))以time函数值(当前时间)作为种子

printf("随机填充5个元素为:

")

while(

i<5)

{

a

=

rand()%100

printf("%d

",

a)

Push(S,a)

i++

}

Print_S(S)

printf("请输入要插入栈顶的元素:")

scanf("%d",&e)

Push(S,e)

Print_S(S)

printf("再弹出的栈顶元素为:%d

\n",Pop(S))

printf("栈的长度为:%d

\n",StackLength(S))

Print_S(S)

return

0

} void

InitStack(SqStack

&S)

//构造空栈S

{

S.base

=

(int

*)malloc(STACK_INIT_SIZE

*

sizeof(int))

//分配组数空间,长度STACK_INIT_SIZE

if

(S.base==NULL)

{

printf("内存分配失败!\n")

return

}

S.top=-1

} int

Push(SqStack

&S,int

e)

{

if(S.top>=STACK_INIT_SIZE)

{

printf("栈空间已满,入栈失败!\n")

return

-1

}

else

{

S.base[++S.top]=e

return

0

}

} int

Pop(SqStack

&S)

//返回栈顶数据

{

if

(S.top>=0)

//栈内有数据

{

return

S.base[S.top--]

}

else

{

printf("空栈,无数据弹出!\n")

return

-1

}

} int

StackLength(SqStack

S)

{

return

S.top+1

} void

Print_S(SqStack

S)

{

printf("\n出栈显示:")

if(S.top

==

-1)

printf("栈内无数据!\n")

else

{

while(S.top>=0

)

printf("%d

",Pop(S))

putchar('\n')

}

}

#include <stdio.h>

#include <stdlib.h>

typedef struct _stack {

int size

int* base

int* sp

} stack

void init(stack* s, int n)

{

s->base = (int*)malloc(sizeof(int)*n)

s->size = n

s->sp = s->base

}

int push(stack* s, int val)

{

if(s->sp - s->base == s->size) {

puts("overflow")

exit(1)

}

return *s->sp++ = val

}

int pop(stack* s)

{

if(s->sp == s->base) {

puts("underflow")

exit(2)

}

return *--s->sp

}

int empty(stack* s)

{

return s->sp == s->base

}

void clean(stack* s)

{

if(s->base)

free(s->base)

}

int main(void)

{

stack s

int i

init(&s, 100)

for(i = 0i <10++i)

printf("%d ", push(&s, i))

putchar('\n')

while(!empty(&s))

printf("%d ", pop(&s))

clean(&s)

return 0

}

#include

<stdio.h>

int

stack[100]

/*100个栈空间*/

int*

sp

=

stack

/*栈指针指向栈底*/

#define

push(

i

)

{

*sp++

=

i

}

/*push一个数*/

#define

pop()

(*--sp)

/*pop一个数并返回*/

int

main()

{

int

i

for

(

i

=

0

i

<

10

++i

)/*push

0~9*/

push(

i

)

for

(

i

=

0

i

<

10

++i

)/*输出9~0*/

printf(

"%d

",

pop()

)

}