Data Structures Examples
Learn to implement common data structures in C programming.
Linked List - Basic Operations
AdvancedDemonstrates basic linked list operations including node creation and insertion.
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
// Function to create a new node
struct Node* createNode(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}
// Function to insert at beginning
void insertAtBeginning(struct Node** head, int data) {
struct Node* newNode = createNode(data);
newNode->next = *head;
*head = newNode;
}
// Function to display linked list
void display(struct Node* head) {
while (head != NULL) {
printf("%d -> ", head->data);
head = head->next;
}
printf("NULL\n");
}
int main() {
struct Node* head = NULL;
insertAtBeginning(&head, 3);
insertAtBeginning(&head, 2);
insertAtBeginning(&head, 1);
printf("Linked List: ");
display(head);
return 0;
}Stack Implementation
IntermediateImplements a stack data structure with push, pop, and display operations.
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100
struct Stack {
int data[MAX_SIZE];
int top;
};
// Initialize stack
void initStack(struct Stack* s) {
s->top = -1;
}
// Check if stack is empty
int isEmpty(struct Stack* s) {
return s->top == -1;
}
// Check if stack is full
int isFull(struct Stack* s) {
return s->top == MAX_SIZE - 1;
}
// Push element to stack
void push(struct Stack* s, int value) {
if (isFull(s)) {
printf("Stack overflow!\n");
return;
}
s->data[++s->top] = value;
}
// Pop element from stack
int pop(struct Stack* s) {
if (isEmpty(s)) {
printf("Stack underflow!\n");
return -1;
}
return s->data[s->top--];
}
// Display stack
void display(struct Stack* s) {
if (isEmpty(s)) {
printf("Stack is empty\n");
return;
}
printf("Stack: ");
for (int i = s->top; i >= 0; i--) {
printf("%d ", s->data[i]);
}
printf("\n");
}
int main() {
struct Stack s;
initStack(&s);
push(&s, 10);
push(&s, 20);
push(&s, 30);
display(&s);
printf("Popped: %d\n", pop(&s));
display(&s);
return 0;
}