0% found this document useful (0 votes)
6 views12 pages

Stack and Queue Implementations in Java

The document provides a series of Java programs that implement various data structures and algorithms, including stack and queue operations using both arrays and linked lists, as well as searching and sorting algorithms like binary search, linear search, quicksort, mergesort, insertion sort, and selection sort. Additionally, it includes programs for evaluating postfix expressions and converting infix expressions to postfix. Each program is presented with its respective class structure and methods for performing the specified operations.

Uploaded by

svsxerox999
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views12 pages

Stack and Queue Implementations in Java

The document provides a series of Java programs that implement various data structures and algorithms, including stack and queue operations using both arrays and linked lists, as well as searching and sorting algorithms like binary search, linear search, quicksort, mergesort, insertion sort, and selection sort. Additionally, it includes programs for evaluating postfix expressions and converting infix expressions to postfix. Each program is presented with its respective class structure and methods for performing the specified operations.

Uploaded by

svsxerox999
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

1. Write a Program to implement stack operations using arrays.

Ans: class StackArray {

int top = -1;

int[] stack = new int[5];

void push(int data) {

if (top == 4) {

[Link]("Stack Overflow");

return;

stack[++top] = data;

void pop() {

if (top == -1) {

[Link]("Stack Underflow");

return;

top--;

}
void display() {

for (int i = 0; i <= top; i++)

[Link](stack[i] + " ");

[Link]();

2. Write a Program to implement stack operations using Linked list.

ans class StackLL {

class Node {

int data;

Node next;

Node(int data) { [Link] = data; }

Node top;

void push(int data) {

Node node = new Node(data);

[Link] = top;

top = node;

}
void pop() {

if (top == null) {

[Link]("Stack Underflow");

return;

top = [Link];

void display() {

Node temp = top;

while (temp != null) {

[Link]([Link] + " ");

temp = [Link];

[Link]();

3. Write a Program to implement queue operations using arrays

Ans: class QueueArray {

int front = 0, rear = 0;


int[] queue = new int[5];

void enqueue(int data) {

if (rear == 5) {

[Link]("Queue Overflow");

return;

queue[rear++] = data;

void dequeue() {

if (front == rear) {

[Link]("Queue Underflow");

return;

front++;

void display() {

for (int i = front; i < rear; i++)

[Link](queue[i] + " ");


[Link]();

4. Write a Program to implement Queue operations using linked list

Ans: class QueueLL {

class Node {

int data;

Node next;

Node(int data) { [Link] = data; }

Node front, rear;

void enqueue(int data) {

Node node = new Node(data);

if (rear == null) front = rear = node;

else {

[Link] = node;

rear = node;

}
void dequeue() {

if (front == null) {

[Link]("Queue Underflow");

return;

front = [Link];

if (front == null) rear = null;

void display() {

Node temp = front;

while (temp != null) {

[Link]([Link] + " ");

temp = [Link];

[Link]();

5. Write a Program to implement Binary Search using recursion

Ans: int binarySearch(int[] arr, int left, int right, int target) {
if (left > right) return -1;

int mid = (left + right) / 2;

if (arr[mid] == target) return mid;

else if (arr[mid] > target)

return binarySearch(arr, left, mid - 1, target);

else

return binarySearch(arr, mid + 1, right, target);

6. Write a Program to implement Linear Search using recursion

Ans: int linearSearch(int[] arr, int index, int target) {

if (index >= [Link]) return -1;

if (arr[index] == target) return index;

return linearSearch(arr, index + 1, target);

7. Write a program to implement quicksort.

Ans: void quickSort(int[] arr, int low, int high) {

if (low < high) {

int pi = partition(arr, low, high);

quickSort(arr, low, pi - 1);

quickSort(arr, pi + 1, high);

}
}

int partition(int[] arr, int low, int high) {

int pivot = arr[high];

int i = low - 1;

for (int j = low; j < high; j++) {

if (arr[j] <= pivot) {

i++;

int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp;

int temp = arr[i+1]; arr[i+1] = arr[high]; arr[high] = temp;

return i + 1;

8. Write a program to implement Merge sort.

Ans: void mergeSort(int[] arr, int l, int r) {

if (l < r) {

int m = (l + r) / 2;

mergeSort(arr, l, m);

mergeSort(arr, m + 1, r);

merge(arr, l, m, r);
}

void merge(int[] arr, int l, int m, int r) {

int[] left = [Link](arr, l, m + 1);

int[] right = [Link](arr, m + 1, r + 1);

int i = 0, j = 0, k = l;

while (i < [Link] && j < [Link])

arr[k++] = left[i] <= right[j] ? left[i++] : right[j++];

while (i < [Link]) arr[k++] = left[i++];

while (j < [Link]) arr[k++] = right[j++];

9. Write a program to implement Insertion sort.

Ans: void insertionSort(int[] arr) {

for (int i = 1; i < [Link]; i++) {

int key = arr[i], j = i - 1;

while (j >= 0 && arr[j] > key) {

arr[j + 1] = arr[j];

j--;

arr[j + 1] = key;
}

10. Write a program to implement Selection sort.

Ans: void selectionSort(int[] arr) {

for (int i = 0; i < [Link] - 1; i++) {

int minIdx = i;

for (int j = i + 1; j < [Link]; j++)

if (arr[j] < arr[minIdx])

minIdx = j;

int temp = arr[minIdx]; arr[minIdx] = arr[i]; arr[i] = temp;

11. Write a Program for the Evaluation of a given postfix expression

Ans: int evaluatePostfix(String expr) {

Stack<Integer> stack = new Stack<>();

for (char c : [Link]()) {

if ([Link](c)) [Link](c - '0');

else {

int b = [Link]();

int a = [Link]();

switch (c) {
case '+': [Link](a + b); break;

case '-': [Link](a - b); break;

case '*': [Link](a * b); break;

case '/': [Link](a / b); break;

return [Link]();

12. Write a program to implement the Infix to Postfix expression

Ans: String infixToPostfix(String expr) {

StringBuilder result = new StringBuilder();

Stack<Character> stack = new Stack<>();

Map<Character, Integer> precedence = [Link]('+', 1, '-', 1, '*', 2, '/', 2, '^', 3);

for (char c : [Link]()) {

if ([Link](c)) [Link](c);

else if (c == '(') [Link](c);

else if (c == ')') {

while (![Link]() && [Link]() != '(')

[Link]([Link]());
[Link]();

} else {

while (![Link]() && [Link](c, 0) <=

[Link]([Link](), 0))

[Link]([Link]());

[Link](c);

while (![Link]()) [Link]([Link]());

return [Link]();

Common questions

Powered by AI

The recursive implementation of Linear Search involves calling a function repeatedly until the target is found or the list is exhausted, which introduces overhead with each recursive call due to function call management but simplifies the logic by reducing loop constructs . Iteratively, the search processes each element sequentially without the recursive framework, resulting in potentially less overhead but with more code complexity. Both methods inherently have O(n) complexity, but recursion can have additional stack overhead .

A stack implemented using arrays handles overflow by checking if the top index has reached the maximum capacity, i.e., the top is equal to the last index of the array. If the condition is met, a 'Stack Overflow' message is printed and further push operations are prevented . For underflow, the implementation checks if the top index is -1, indicating the stack is empty. If so, a 'Stack Underflow' message is printed and pop operations are stopped .

QuickSort typically performs better on average due to its ability to divide and conquer the problem in an efficient manner, sorting sub-arrays independently, which allows for optimal average time complexity of O(n log n). The partition method is crucial because it chooses a pivot and rearranges elements in such a way that all elements less than the pivot end up on one side and those greater on the other, ensuring that subsequent recursive sorts operate on smaller sections of the array, generally leading to more balanced and efficient sorting .

Using recursion for Binary Search offers a more straightforward implementation as it elegantly divides the search space using a recursive function call. This approach lends itself well to the divide-and-conquer paradigm that the algorithm embodies . Compared to an iterative approach, recursion eliminates the need for a looping construct and can make the code smaller and simpler to read, though it can introduce overhead due to function call stack maintenance, potentially impacting performance in environments with limited stack size .

Merge Sort ensures efficiency with a time complexity of O(n log n) by repeatedly dividing the array in half, sorting each half, and merging them back together . The algorithm is stable because the merge function merges elements from two sub-arrays in sorted order while preserving the relative order of equal elements from the original arrays, ensuring that the original sequence of equal elements is maintained during merging . This function is pivotal as it enables effective merging of sorted subarrays into a fully sorted array, maintaining order and efficiency.

Stacks are central to evaluating postfix expressions by holding intermediate results and operators. As each token in the expression is processed, operands are pushed to the stack, and operators trigger operations on the top elements, popping them off, evaluating, and pushing the result . This method sequentially evaluates the postfix string in a single pass, efficiently utilizing stack properties to manage operations and order of execution within constraints of operator precedence and operand availability .

In array-based queue implementations, primary challenges include managing fixed capacity, risking overflow as the rear index cannot proceed past the fixed limit of the array size, and causing inefficient space utilization once elements are dequeued . In contrast, a linked list implementation dynamically adjusts to the number of elements, facilitated by nodes that allow the queue to grow as necessary until system memory limits are reached. This setup avoids overflow due to capacity restrictions and uses memory only as needed for actual data, albeit with additional overhead for node management .

Converting infix expressions to postfix removes the need for parentheses to denote precedence and allows evaluations using simpler and more efficient algorithms like postfix evaluation . Operator precedence is managed by maintaining a stack where operators are pushed or popped based on their precedence and associativity, ensuring that higher precedence operators are resolved before lower precedence ones, and operators follow their left or right associative rules as determined during the infix parsing .

In an array-based stack, push and pop operations are done by directly manipulating indices within a fixed-size array. This means that the stack's size is limited to the array's size and thus prone to overflow when full . In contrast, a linked-list-based stack dynamically allocates space using nodes, allowing the stack to grow and shrink as necessary without the same overflow constraint, although it can encounter memory issues on a system level if resources are exhausted . Linked lists require additional memory for node pointers but afford greater flexibility in terms of size changes.

Designing an efficient sorting algorithm requires considering factors like time complexity (e.g., average and worst-case scenarios), stability (preserving order of equal elements), space complexity, adaptability to partially sorted data, and overhead related to recursion or iteration, especially for varying data sizes . Additionally, choosing the most fitting algorithm, such as QuickSort for average cases or MergeSort for stable sorts, must also account for the hardware constraints—memory limits and processor load—as these fundamentally impact the feasible performance of the solution across varied data types and conditions .

You might also like