May 11, 2023

Linked List Uses

This is a description

Stacks Using LL

#include <stdio.h>
#include <stdlib.h>

struct Node
{
	int data;
	struct Node *next;
};

struct Stack
{
	struct Node *top;
};

struct Node *createNode(int data)
{
	struct Node *newNode = (struct Node *)malloc(sizeof(struct Node));
	newNode->data = data;
	newNode->next = NULL;
	return newNode;
}

void push(struct Stack *stack, int data)
{
	struct Node *newNode = createNode(data);
	newNode->next = stack->top;
	stack->top = newNode;
}

int pop(struct Stack *stack)
{
	if (stack->top == NULL)
	{
		printf("Error: Stack is empty\n");
		return -1; // Return an error value
	}
	struct Node *temp = stack->top;
	int data = temp->data;
	stack->top = temp->next;
	free(temp);
	return data;
}

int isEmptyStack(struct Stack *stack)
{
	return stack->top == NULL;
}

void main()
{
	struct Stack stack;
	stack.top = NULL;

	push(&stack, 1);
	push(&stack, 2);
	push(&stack, 3);

	printf("Stack: ");
	while (!isEmptyStack(&stack))
	{
		printf("%d ", pop(&stack));
	}
	printf("\n");
}

Queues Using LL

#include <stdio.h>
#include <stdlib.h>

struct Node
{
	int data;
	struct Node *next;
};

struct Queue
{
	struct Node *front;
	struct Node *rear;
};

struct Node *createNode(int data)
{
	struct Node *newNode = (struct Node *)malloc(sizeof(struct Node));
	newNode->data = data;
	newNode->next = NULL;
	return newNode;
}

void enqueue(struct Queue *queue, int data)
{
	struct Node *newNode = createNode(data);
	if (queue->rear == NULL)
	{
		queue->front = newNode;
		queue->rear = newNode;
	}
	else
	{
		queue->rear->next = newNode;
		queue->rear = newNode;
	}
}

int dequeue(struct Queue *queue)
{
	if (queue->front == NULL)
	{
		printf("Error: Queue is empty\n");
		return -1; // Return an error value
	}
	struct Node *temp = queue->front;
	int data = temp->data;
	queue->front = temp->next;
	if (queue->front == NULL)
	{
		queue->rear = NULL; // Reset rear when queue becomes empty
	}
	free(temp);
	return data;
}

int isEmpty(struct Queue *queue)
{
	return queue->front == NULL;
}

void main()
{
	struct Queue queue;
	queue.front = NULL;
	queue.rear = NULL;

	enqueue(&queue, 1);
	enqueue(&queue, 2);
	enqueue(&queue, 3);

	printf("Queue: ");
	while (!isEmpty(&queue))
	{
		printf("%d ", dequeue(&queue));
	}
	printf("\n");
}