142k views
3 votes
In your own words, describe the structure and function of both the stack and queue data structure and discuss how they are different from the perspective of how they are used.

User Zia Khan
by
3.2k points

1 Answer

3 votes

Answer:

Following are the answer to this question:

Step-by-step explanation:

Stack:

The stack data structure is used to create method, parsing, analysis of expression, and tracking. This data type uses the LIFO system, which stands from the Last In First Out. This data structure operates on the top side. In this data structure, it performs two methods, that are "push() and pop()" method and the time complexity of the stack data structure O(1).

Example of Stack:

import java.util.*;//import package

public class Main //defining class Main

{

public static void main (String[] ag)//defining main method

{

ArrayDeque<Character> stack = new ArrayDeque<Character>();//creating Character array ArrayDeque

stack.push('A'); //add value in stack

stack.push('B');//add value in stack

stack.push('B'); //add value in stack

System.out.println("First Insert:"+stack); //print value stack.pop();//remove value from stack

System.out.println("After removing element: "+stack); //print value stack.push('B'); //add value in stack

stack.pop();//remove value from stack

System.out.println("final value: "+stack); //print value

}

}

Output:

First Insert:[B, B, A]

After removing element: [B, A]

final value: [B, A]

Queue:

The queue data structure is an abstract type, it is similar to the stacks data structure. It is open at both ends when opposed to lines. It follows the FIFO method, which stands for the First-In-First-Out method, At one end data is inserted and at the other end, it deletes the data and the time complexity of the queue data structure O(1).

Example of Queue:

import java.util.*;//import package

public class Main//defining a class queue

{

public static void main(String[] ars)//defining main method

{

LinkedList<Integer> que= new LinkedList<Integer>();//defining integer array LinkedList

for (int i = 0; i < 5; i++)//defining fo loop to add value in queue

{

que.add(i); //use add method to insert value

}

System.out.println("Queue value: "+ que); //print queue value

int remove= que.remove(); //remove value from the queue System.out.println("after removing value from queue: "+ remove);//removing element from queue

System.out.println(que); //after removing the element print value

}

}

Output:

Queue value: [0, 1, 2, 3, 4]

after removing value from queue: 0

[1, 2, 3, 4]

User Dasup
by
3.6k points