Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,847 questions

51,768 answers

573 users

How to implement stack that push and pops node struct with pointers and memory allocation in C

1 Answer

0 votes
#include <stdio.h>
#include <stdlib.h>

struct stack
{
    struct node *head;
    int size;
};

struct node
{
    int n;
    struct node *next;
};

int push(int, struct stack*);
int pop(struct stack*);
void print(struct stack *stack);
void free_memory(struct stack*);
 
int main(void)
{
    int result = EXIT_SUCCESS;

    struct stack *stack = malloc(sizeof *stack);
    if (NULL == stack)
    {
        perror("malloc() error");
        return EXIT_FAILURE;
    }

    stack->head = NULL;
    stack->size = 0;
    
    {
        int n = 0;
        // push 5 ints 
        for (size_t i = 0; i < 5; i++)
        {
            if (push(n, stack) == -1)
            {
                perror("push() error");
                result = EXIT_FAILURE;
                break;
            }
            n++;
        }
        print(stack);
    }

    if (EXIT_SUCCESS == result)
    {
        // pop 2 ints 
        for (size_t i = 0; i < 2; i++)
            pop(stack);
            
        print(stack);
    }

    free_memory(stack);
    
    print(stack);

    return result;
}

int push(int n, struct stack *stack)
{
    struct node *new_node = malloc(sizeof *new_node);
    if (new_node == NULL)
       return -1;
    else
    {
        new_node->n = n;
        new_node->next = stack->head;
        stack->head = new_node;
        stack->size++;
    }

    return 0;
}

int pop(struct stack *stack)
{
    struct node *head = stack->head;
    int n = head->n;
    
    stack->head = head->next;
    stack->size--;
    free(head);
    
    return n;
}

void print(struct stack *stack)
{
    struct node *head = stack->head;
    
    while (head)
    {
        printf("%3d", head->n);
        head = head->next;
    }
    printf("\n");
}

void free_memory(struct stack *stack)
{
    while (stack->head != NULL)
        pop(stack);
}
   
    
/*
run:
    
  4  3  2  1  0
  2  1  0
    
*/

 



answered Aug 13, 2017 by avibootz

Related questions

1 answer 129 views
1 answer 155 views
155 views asked Dec 27, 2020 by avibootz
1 answer 157 views
157 views asked Jul 26, 2017 by avibootz
1 answer 248 views
...