c语言写一个数组栈

Python022

c语言写一个数组栈,第1张

#include <stdio.h>

#include <stdlib.h>

#define Size 20

typedef char ElementType

typedef struct

{

    ElementType    data[Size]

    int top

}Stack    

int  StackFull(Stack *s)

{

    return (s->top==Size-1)

}

void PushStack(Stack *s, char *buf)

{

    if(NULL==s || NULL==buf)

        return

    while( *buf!='\0' && *buf!='^' && !StackFull(s))

    {

        if(*buf != ' ')

            s->data[++s->top] = *buf

        ++buf    

    }

}

void PopStack(Stack *s)

{

    if(NULL == s)

        return

    while(s->top != -1)

        putchar(s->data[s->top--])

}

int main()

{

    char str[Size]

    Stack *s = (Stack*)malloc(sizeof(Stack))

    s->top = -1

    

    gets(str)

    PushStack(s, str)

    PopStack(s)

                  

    return 0

}

#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

}