I have made a few functions for some basic stack operations using linked lists. Please review my code and suggest some ways to increase its readability. I would also love to hear ideas on how to make my code more compact and simple.
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
};
void Traversal(struct node *ptr)
{
do
{
printf("The element is : %d\n", ptr->data);
ptr = ptr->next;
} while (ptr->next != NULL);
}
int isEmpty(struct node *top)
{
if (top == NULL)
{
return 1;
}
else
{
return 0;
}
}
int isFull(struct node *top)
{
struct node *n = malloc(sizeof(struct node *));
if (n == NULL)
{
return 1;
}
else
{
return 0;
}
free(n);
}
struct node *push(struct node *top, int x)
{
if (isFull(top))
{
printf("Stack Overflow\n");
}
else
{
struct node *n = malloc(sizeof(struct node));
n->data = x;
n->next = top;
top = n;
}
return top;
}
struct node *pop(struct node *top)
{
if (isEmpty(top))
{
printf("Stack Underflow\n");
}
else
{
struct node *n = top;
top = top->next;
free(n);
}
return top;
}
struct node *peek(struct node *top, int atPosition) // To view the value stored at a specific postion
{
struct node *ptr = top;
if (atPosition < 0)
{
printf("Invalid Index\n");
}
else
{
for (int i = 1; i < atPosition && ptr->next != NULL; i++)
{
ptr = ptr->next;
}
printf("The data at index %d is %d\n", atPosition, ptr->data);
}
free(ptr);
return top;
}
struct node *stackTop(struct node *top)
{
printf("The data stored in stack top is %d\n", top->data);
return top;
}
struct node *stackBottom(struct node *top)
{
struct node *ptr = top;
while (ptr->next != NULL)
{
ptr = ptr->next;
}
printf("The data stored in stack bottom is %d\n", ptr->data);
free(ptr);
return top;
}