I am trying to implement stack as a linked list. Here is my current code:
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
typedef struct node {
int data;
struct node* link;
} Node;
typedef Node* list;
list head;
void push(list top, int item) {
if (head == NULL) {
head = (list) malloc(sizeof(Node));
head->data = item;
head->link = NULL;
top = head;
} else{
list temp = (list) malloc(sizeof(Node));
temp->data = item;
temp->link = top;
top = temp;
}
}
int pop(list top) {
if (top == NULL) {
printf("stack is empty");
/*int tdata=top->data;
top=top->link;
return tdata;*/
} else {
int tdata = top->data;
top = top->link;
return tdata;
}
}
void display(list top){
while (top != NULL) {
printf("%d", top->data);
top = top->link;
}
}
int main() {
int ch, item;
list top;
for (;;) {
printf("1.push\t2.pop\t3.display\t4.exit");
scanf("%d", &ch);
switch (ch) {
case 1:
printf("enter the element to be pushed");
scanf("%d",&item);
push(top,item);
break;
case 2:
item=pop(top);
printf("element popped is: %d",item);
break;
case 3:
display(top);
break;
case 4:
exit(0);
break;
default:
printf("enter valid choice");
}
}
}
When I press '2' the pop method is called, but irrespective of whatever item is on the top it prints the message "element popped is: 11". When I press '3' for the display method, I get "segmentation fault(core dumped)". Why is this happening? What modifications are needed to get this code working?
top(main) orhead(global).typedefa pointer. As a result, inpushyour list head is not finding its way back totopinmain, it only alters the local copy, while inmainthe local vartopremains uninitialised giving undefined behaviour.popyou do notfreethe memory that was allocated.