How to implement Linked List Using Stack?
How to implement Linked List Using Stack?
To implement a stack using a linked list, you need to understand the basic operations of a stack (push, pop, peek) and how they can be mapped to operations on a linked list. Here is a detailed explanation and example code in C for implementing a stack using a singly linked list.
Stack: A linear data structure that follows the Last In, First Out (LIFO) principle. The main operations are:
Linked List: A data structure consisting of nodes where each node contains data and a reference (link) to the next node in the sequence. In a singly linked list, each node points to the next node, and the last node points to NULL
.
data
and next
.top
to keep track of the top of the stack.top
pointer.top
pointer is NULL
.#include <stdio.h>
#include <stdlib.h>
// Define the node structure
struct Node {
int data;
struct Node* next;
};
// Initialize the top of the stack
struct Node* top = NULL;
// Function to push an element onto the stack
void push(int value) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
if (newNode == NULL) {
printf("Stack overflow\n");
return;
}
newNode->data = value;
newNode->next = top;
top = newNode;
printf("Pushed %d onto the stack\n", value);
}
// Function to pop an element from the stack
void pop() {
if (top == NULL) {
printf("Stack underflow\n");
return;
}
struct Node* temp = top;
printf("Popped %d from the stack\n", temp->data);
top = top->next;
free(temp);
}
// Function to peek the top element of the stack
int peek() {
if (top == NULL) {
printf("Stack is empty\n");
return -1;
}
return top->data;
}
// Function to check if the stack is empty...
junior
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào