#include <stdio.h>
#include <stdlib.h>
typedef struct x {
int data;
struct x *next;
} stack;
int main(){
stack *head;
int choice, num;
head = NULL;
/* function prototypes */
void push(stack **head, int item);
int pop(stack **head);
int peek(stack *head);
/* program */
do{
printf("\n1. Push Element\n2. Pop Element\n3. Peek The First Element\n4. Exit");
printf("\nEnter your choice: ");
scanf("%d", &choice);
switch(choice){
case 1:
printf("\n\nEnter the number to be pushed: ");
scanf("%d", &num);
push(&head, num);
break;
case 2:
printf("%d\n", pop(&head));
break;
case 3:
printf("%d is the top element\n", peek(head));
break;
default:
system("cls");
break;
}
}while(choice!=4);
}
void push(stack **head, int item){
stack *ptr;
ptr = (stack *)malloc(sizeof(stack));
ptr->data = item;
ptr->next = *head;
*head = ptr;
free(ptr);
}
int pop(stack **head){
if(*head == NULL) return -1;
int item = (*head)->data;
*head = (*head)->next;
return item;
}
int peek(stack *head){
if(head == NULL) return -1;
return head->data;
}
What is the problem in the code? Whenever I pop or peek a memory address is being printed instead of the value pushed. When peek is called a memory address is shown which is popped when pop function is called and after that whenever calling the pop function it shows different memory address no matter how many times i call the function. Can't find out the problem in the code. Please help.