#include <stdio.h>
#include <stdlib.h>
// Node structure for linked list
typedef struct Node {
int data;
struct Node* next;
} Node;
// Function to push a new node at the front
void push(Node** head_ref, int new_data) {
Node* new_node = (Node*)malloc(sizeof(Node));
new_node->data = new_data;
new_node->next = *head_ref;
*head_ref = new_node;
}
// Function to pop the first node and return its data
int pop(Node** head_ref) {
if (*head_ref == NULL) {
return -1; // List empty
}
Node* temp = *head_ref; // store current head
int popped_data = temp->data;
*head_ref = temp->next; // move head to next node
temp->next = NULL; // disconnect old head
free(temp); // free memory
return popped_data;
}
// Function to print the list
void printList(Node* head) {
Node* curr = head;
while (curr != NULL) {
printf("%d -> ", curr->data);
curr = curr->next;
}
printf("null\n");
}
int main() {
Node* head = NULL;
push(&head, 3);
push(&head, 2);
push(&head, 1);
printf("Original list: ");
printList(head);
int popped = pop(&head);
printf("Popped value: %d\n", popped);
printf("List after pop: ");
printList(head);
return 0;
}Node* temp = *head_ref; // store current head
store the first node to return its data later
*head_ref = temp->next; // move head to next node
update head pointer to next node to remove first node
temp->next = NULL; // disconnect old head
disconnect old head from list to avoid dangling pointer
free(temp); // free memory
release memory of removed node
Original list: 1 -> 2 -> 3 -> null
Popped value: 1
List after pop: 2 -> 3 -> null