Anda di halaman 1dari 3

#include <stdio.

h>
#include <stdlib.h>
#include <string.h>
enum { STACK_ARR_SIZE = 10 };
struct my_stack
{
char arrc[STACK_ARR_SIZE];
struct my_stack* next;
};
struct stack_list
{
struct my_stack* head;
};

struct stack_list* push( struct stack_list*, const char* );


struct stack_list* pop( struct stack_list* );
struct stack_list* top( struct stack_list* );
struct stack_list* stack_new( void );
void stack_print( const struct stack_list* );
void stack_print_element( const struct my_stack* );
void stack_free( struct my_stack* );

int main( void )


{
struct stack_list* ms = NULL;
ms = stack_new();
stack_print(ms);
push(ms, "comp");
push(ms, "(dot)");
push(ms, "lang");
push(ms, "(dot)");
push(ms, "c");
stack_print(ms);

return 0;
}

struct stack_list* push(struct stack_list* s, const char* c )


{
struct my_stack* p = malloc( 1 * sizeof *p );
struct my_stack* n = NULL;
if( NULL == p )
{
fprintf(stderr, "malloc() failed\n");
return s;
}
strcpy(p->arrc, c);
p->next = NULL;
if( NULL == s )
{
fprintf(stderr, "Stack not initialized ?\n");
return s;
}
else if( NULL == s->head )
{
/* printf("Stack is Empty, adding first element\n"); */
s->head = p;
return s;
}
else
{
/* printf("Stack not Empty, adding in front of first element\n"); */
n = s->head; /* save current head */
s->head = p; /* push new element onto the head */
s->head->next = n; /* attach the earlier saved head to the next of new element *
/
}
return s;
}

/* ---------- small helper functions -------------------- */


struct stack_list* stack_new( void )
{
struct stack_list* p = malloc( 1 * sizeof *p );
if( NULL == p )
{
fprintf(stderr, "malloc() in Stack Initialization failed\n");
}
p->head = NULL;
return p;
}

void stack_print( const struct stack_list* s )


{
struct my_stack* p = NULL;
if( NULL == s )
{
printf("Can not print an Empty Stack\n");
}
else
{
for( p = s->head; p; p = p->next ) stack_print_element(p);
}
}

void stack_print_element(const struct my_stack* s)


{
printf("arrc = %s\n", s->arrc);
}