[Go to site: main page, start]

0% found this document useful (0 votes)
11 views6 pages

Java Stack and Queue Implementations

The document contains Java programs demonstrating data structures such as stacks and queues using both linked lists and arrays, along with a postfix evaluation example. Each program includes code snippets that showcase operations like push, pop, enqueue, and dequeue, as well as evaluating a postfix expression. The examples are designed to be run using an online compiler.

Uploaded by

rvicky11102006
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)
11 views6 pages

Java Stack and Queue Implementations

The document contains Java programs demonstrating data structures such as stacks and queues using both linked lists and arrays, along with a postfix evaluation example. Each program includes code snippets that showcase operations like push, pop, enqueue, and dequeue, as well as evaluating a postfix expression. The examples are designed to be run using an online compiler.

Uploaded by

rvicky11102006
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

Programs in Java

Run using one compiler (online)

1. Stack using LinkedList

2. Stack using Array

3. Queue using LinkedList

4. Queue using Array

5. Postfix Evaluation
1. Stack using LinkedList
import [Link].*;

public class Stackll {


public static void main(String args[]) {

LinkedList<Integer> s = new LinkedList<Integer>();

[Link](10);
[Link](20);
[Link](30);
[Link](40);
[Link](50);

[Link]("Initial Stack: " + s);


[Link]("The element at the top of the Stack is: " +
[Link]());

[Link]();
[Link]("The elements in Stack after pop: " + s);
[Link]("The size of the Stack is: " + [Link]());
}
}
2. Stack using Array

import [Link].*;

public class StackArray {


public static void main(String args[]) {
int maxSize = 5;
int[] stack = new int[maxSize];
int top = -1;

// Push elements
stack[++top] = 10;
stack[++top] = 20;
stack[++top] = 30;
stack[++top] = 40;
stack[++top] = 50;

[Link]("Initial Stack: ");


for (int i = top; i >= 0; i--) {
[Link](stack[i] + " ");
}
[Link]();

// Peek element
[Link]("The element at the top of the Stack is: " +
stack[top]);

// Pop operation
top--;
[Link]("The elements in Stack after pop: ");
for (int i = top; i >= 0; i--) {
[Link](stack[i] + " ");
}
[Link]();

// Size of stack
[Link]("The size of the Stack is: " + (top + 1));
}
}
3. Queue using Linked List
import [Link].*;

public class Queuell {


public static void main(String args[]) {

Queue<Integer> q = new LinkedList<Integer>();

[Link](10);
[Link](20);
[Link](30);
[Link](40);
[Link](50);

[Link]("Initial Queue: " + q);

[Link]("The element at the front of the Queue is: " +


[Link]());

[Link]();
[Link]("The elements in Queue after dequeue: " + q);

[Link]("The size of the Queue is: " + [Link]());


}
}
4. Queue using Array
import [Link].*;

public class QueueArray {


public static void main(String args[]) {
int maxSize = 5;
int[] queue = new int[maxSize];
int front = 0, rear = -1, size = 0;

// Enqueue elements
queue[++rear] = 10;
size++;
queue[++rear] = 20;
size++;
queue[++rear] = 30;
size++;
queue[++rear] = 40;
size++;
queue[++rear] = 50;
size++;

[Link]("Initial Queue: ");


for (int i = front; i <= rear; i++) {
[Link](queue[i] + " ");
}
[Link]();

// Peek element
[Link]("The element at the front of the Queue is: " +
queue[front]);

// Dequeue operation
front++;
size--;

[Link]("The elements in Queue after dequeue: ");


for (int i = front; i <= rear; i++) {
[Link](queue[i] + " ");
}
[Link]();

// Size of Queue
[Link]("The size of the Queue is: " + size);
}
}
5. Postfix Evaluation

import [Link].*;

public class Eval {


static int evaluate(String exp) {
Stack<Integer> s = new Stack<>();

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


char c = [Link](i);

if ([Link](c)) {
[Link](c - '0'); // Convert char digit to int
} else {
int val1 = [Link]();
int val2 = [Link]();

if (c == '+')
[Link](val2 + val1);
else if (c == '-')
[Link](val2 - val1);
else if (c == '*')
[Link](val2 * val1);
else if (c == '/')
[Link](val2 / val1);
}
}
return [Link]();
}

public static void main(String[] args) {


String exp = "23-";
[Link]("Postfix Expression: " + exp);
[Link]("Postfix Evaluation: " + evaluate(exp));
}
}

Common questions

Powered by AI

Postfix evaluation uses a stack to temporarily hold operands until an operator is encountered. When an operator is found, the stack pops the necessary number of operands (usually two), executes the operation, and pushes the result back onto the stack. This approach efficiently manages operations without needing additional precedence rules or parentheses, as the stack ensures the correct order of operations due to its LIFO nature. Each operand or result is pushed and popped as required, utilizing the stack's characteristics to maintain proper sequencing and handling intermediate results .

The code organizes postfix evaluation by iterating over each character of the expression, determining if it is a digit or operator. Digits are converted to integers and pushed onto a stack. When an operator is encountered, the code pops two operands from the stack, applies the operator, and pushes the result back. This sequence continues until the full expression is processed, culminating in the final result left on the stack. This systematic approach ensures operands are always available for any operator encountered in sequence .

Manually managing indices in an array-based stack or queue can lead to errors such as out-of-bounds access, overflow, and off-by-one mistakes during insertion or removal operations. Linked lists alleviate these issues by abstracting index management; nodes dynamically link via pointers, thus facilitating easy insertion and deletion without concern for size limits or index handling. This enables straightforward element management but may introduce overhead due to the additional memory needed for pointer storage .

Converting character digits to integers is crucial in postfix evaluation to enable mathematical operations since numerical computation requires integer values. In Java, this conversion is done by subtracting the ASCII value of '0' from the character. For example, `'0'` has an ASCII value of 48, so subtracting this value from any digit character converts it from a character type to its integer form, facilitating easy arithmetic operations .

A queue implemented via a linked list maintains elements as nodes linked sequentially, where operations like 'enqueue' and 'dequeue' simply involve updating node pointers, preserving order dynamically. Conversely, an array-based queue treats the structure as a ring buffer; elements are stored in a contiguous block of memory and managed with indices that wrap around as elements are enqueued or dequeued. This requires manual index management to handle overflow or underflow conditions, unlike the dynamic nature of linked lists .

The 'peek' operation allows access to the element at the top of the stack or the front of the queue without removing it. In the array-based stack implementation, 'peek' is performed by accessing the element at the 'top' index, whereas in a linked list stack, it's done using the 'peek()' method of the LinkedList class. For queues, 'peek' similarly accesses the front element, with the method differing slightly by data structure: array uses the 'front' index, while a linked list queue uses the 'peek()' method .

When using an array, a stack is implemented with a fixed maximum size, and elements are added and removed using the top index. This requires manual management of index boundaries to avoid stack overflows. In contrast, a linked list implementation dynamically manages elements using nodes, allowing for theoretically unlimited size, as nodes are created and removed dynamically. The linked list might incur a slight overhead due to reference management but avoids the fixed-size limitation of arrays .

Implementing stacks using arrays introduces the risk of stack overflow, as the stack has a fixed maximum size. This can be mitigated by either increasing the array size dynamically, which complicates implementation, or by using a sufficiently large array from the start, though this may lead to inefficient memory use. Another limitation is that the predefined size requires precise knowledge of stack size requirements, which might not always be feasible. A potential workaround is using dynamic data structures like linked lists for more flexible memory usage .

In an array-based queue, enqueueing involves inserting an element at the rear, updating the index accordingly, and perhaps handling the wrap-around in a circular fashion if the end of the array is reached. Dequeueing involves removing the element at the front and incrementing the front index. The rationale is to utilize contiguous memory for efficient access, but it requires explicit index management to avoid overwriting elements. This method also often includes size tracking to distinguish between empty and full states .

Implementing queues using arrays involves managing a fixed-size buffer, which can lead to complexity in handling circular queues and potential overflow if not resized or managed properly. It requires manually updating front and rear indices. Conversely, linked list implementations are inherently flexible, supporting dynamic resizing without concern for overflow or size management since elements are stored as nodes connected via pointers. Linked lists incur extra memory for storing pointers and potentially more complex deallocation processes, but they provide better adaptability for varying sizes .

You might also like