Stack Using Linked List
Implementation of a stack using linked list and its functions.
struct Node {
int data;
struct Node *next;
};
struct Node *top = NULL;
int isEmpty() {
return top == NULL;
}
void push(int data) {
// Creating a new stack node
struct Node *newNode;
newNode = (struct Node *)malloc(sizeof(struct Node));
newNode -> data = data;
// Set the next to point to current top
newNode -> next = top;
// Update top
top = newNode;
}
int pop() {
if (isEmpty()) {
printf("Stack underflow !\n");
return -1;
}
struct Node *toDelete = top;
int poppedValue = top -> data;
top = top -> next;
free(toDelete);
return poppedValue;
}
int peek() {
return top -> data;
}
void display() {
if (isEmpty()) {
printf("Stack is empty\n");
return;
}
struct Node *ptr = top;
while (ptr != NULL) {
printf("%d\t", ptr -> data);
ptr = ptr -> next;
}
printf("\n");
}
Contributed by Nitin Ranganath
Last modified 3yr ago