1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

stack implementation with linked list in c

Discussion in 'Programming/Internet' started by Ivan Stimac, Oct 8, 2018.

  1. Ivan Stimac

    Ivan Stimac Guest

    currently I am following CS50 course (now I am going thorough data structures chapter). This is my implementation of stack with linked list:

    // This program is implementation of stack data structure
    // via linked list (LAST IN FIRST OUT STRUCTURE) LIFO

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>

    typedef struct node
    {
    char string[20];
    struct node *next;
    } node;

    node *push(char *element, node *head);
    node *pop(node *head);
    void destroy_stack(node *p);

    int main(void)
    {


    // create new stack
    node *stack = NULL;

    // push 6 "functions" to the stack
    char *function[6] = {"first funct", "second funct", "third funct",
    "fourth funct", "fifth funct", "sixt funct"};
    for (int i = 0; i < 6; i++)
    {
    printf("function is : %s\n",function);
    stack = push(function, stack);
    if (!stack)
    {
    fprintf(stderr,"Not enough memory space for new list");
    return 1;
    }
    }


    // display the stack
    for (node *temp = stack; temp != NULL; temp = temp -> next)
    {

    printf("Elements of the stack are: %s\n", temp -> string);
    }

    // pop the elements from the stack
    while (stack != NULL)
    {

    printf("Popped elemet is: %s\n", stack -> string);
    stack = pop(stack);


    }

    destroy_stack(stack);
    return 0;

    }

    node *push(char *element, node *head)
    {
    // create space for new element on stack
    node *temp = malloc(sizeof(node));
    if (!temp)
    {
    return NULL;
    }

    // if stack is empty
    if (head == NULL)
    {
    strcpy(temp -> string, element);
    temp -> next = NULL;
    return temp;
    }

    strcpy(temp -> string, element);
    temp -> next = head;
    return temp;
    }

    node *pop(node * head)
    {
    // create a new head
    node *newHead = head->next;

    // pop the element from stack
    free(head);

    return newHead;

    }

    void destroy_stack(node *p)
    {
    if ( p == NULL )
    {
    return;
    }
    else
    {
    destroy_stack(p -> next);
    }
    free(p);
    }


    My question is the implementation good and I wanted to check if my understandig of what stack is is ok

    Login To add answer/comment
     

Share This Page