Question

Create a Stack class based on java.util.LinkedList class. Your Stack class should have a push(), pop(),...

Create a Stack class based on java.util.LinkedList class. Your Stack class should have a push(), pop(), peek(), and isEmpy() methods.
Create a new Java Application that has the following methods.

Write a method reverseChar() to print a sentence in reverse order. Use a Stack to reverse each character. Example: if the user enters a sentence “ABC DEFG”, the program will display “GFED CBA”

Write a method reverseWord() to print a sentence reverse order. Use a Stack to reverse each word. Example: If the user enters a sentence "Live and Let Live" the program will display "Live Let and Live"

Write a method to randomly generate a number of elements between two given values and save them in a stack.

Write a method to print a stack (10 elements per line). The original stack should remain as is after the print.

Write a method to return the number of elements on the stack (without changing the stack).

Write a method to search for a value in a stack. The stack should remain the same after the search is finished.

Write a method to print the second element of the stack and leave the original stack unchanged

Write a method to count the number of elements in a stack that are larger than a given value and leave the original stack unchanged.

Write a method peekLowestElement() to return the smallest element. The original stack should remain unchanged.

10. Write a method peekHighestElement() to return the largest element. The original stack should remain unchanged.

11. Write a method to return the inverse a stack. The original stack should remain unchanged.
12. Write a method to make a copy of a stack into another stack and return it. The original stack should remain

unchanged.

In the main method test all your methods including the following cases:

Create 2 Stacks S1, S2

Insert 20 integers between 20 and 60 (do not insert duplicates) into S1

Insert 30 integers between 10 and 80 (do not insert duplicates) into S2.

Test all your methods using S1 and S2

1 0
Add a comment Improve this question Transcribed image text
Answer #1

===============StackL.java==============

package stack_impl;

import java.util.Iterator;

import java.util.LinkedList;

import java.util.NoSuchElementException;

/**

* The Class StackL.

*

* @param <T> the generic type

*/

public class StackL<T> implements Iterator<T> {

/** The stack. */

private LinkedList<T> stack;

/** The position. */

private int position = 0;

/**

* Instantiates a new stack L.

*/

public StackL() {

stack = new LinkedList<>();

}

/**

* Push.

*

* @param element the element

*/

public void push(T element) {

stack.push(element);

}

/**

* Pop.

*

* @return the t

*/

public T pop() {

return stack.pop();

}

/**

* Checks if is empty.

*

* @return true, if is empty

*/

public boolean isEmpty() {

return stack.isEmpty();

}

/**

* Size.

*

* @return the int

*/

public int size() {

return stack.size();

}

/**

* Peek last.

*

* @return the t

*/

public T peekLast() {

return stack.peekLast();

}

/**

* Peek first.

*

* @return the t

*/

public T peekFirst() {

return stack.peekFirst();

}

/*

* (non-Javadoc)

*

* @see java.util.Iterator#hasNext()

*/

@Override

public boolean hasNext() {

if (position < stack.size())

return true;

else

return false;

}

/*

* (non-Javadoc)

*

* @see java.util.Iterator#next()

*/

@Override

public T next() {

if (this.hasNext()) {

return stack.get(position++);

}

else {

throw new NoSuchElementException();

}

}

}

================MyStackStringDriver.java========

package stack_impl;

public class MyStackStringDriver {

public static void main(String[] args) {

reverseChar();

reverseWord();

}

private static void reverseWord() {

String input = "Live and Let Live";

String[] words = input.split(" ");

StackL<String> myCharacterStack = new StackL<>();

for (String c : words) {

myCharacterStack.push(c);

myCharacterStack.push(" ");

}

while (myCharacterStack.hasNext()) {

System.out.print(myCharacterStack.next());

}

System.out.println();

}

private static void reverseChar() {

String chars = "ABC DEFG";

char[] charValues = chars.toCharArray();

StackL<Character> myCharacterStack = new StackL<>();

for (char c : charValues) {

myCharacterStack.push(c);

}

while (myCharacterStack.hasNext()) {

System.out.print(myCharacterStack.next());

}

System.out.println();

}

}

output:

tive let and Live Live Let and Live

=======================MyStackNumberDriver.java=======================

package stack_impl;

import java.util.Random;

/**

* The Class MyStackNumberDriver.

*/

public class MyStackNumberDriver {

/**

* The main method.

*

* @param args the arguments

*/

public static void main(String[] args) {

StackL<Integer> s1 = new StackL<>();

StackL<Integer> s2 = new StackL<>();

generateRandomNumber(s1, 20, 60, 20);

generateRandomNumber(s2, 10, 80, 30);

printTenElements(s1);

printSizeOfStack(s1);

findValue(s1, 20);

printSecondElementOfStack(s2);

countNumberOfLargerElemets(s2, 30);

peekLowestElement(s2);

peekHighestElement(s1);

createCopy(s1);

}

/**

* Creates the copy.

*

* @param stack the stack

* @return the stack L

*/

private static StackL<Integer> createCopy(StackL<Integer> stack) {

StackL<Integer> newStack = new StackL<>();

while (stack.hasNext()) {

int value = stack.next();

newStack.push(value);

}

return newStack;

}

/**

* Inverse stack.

*

* @param stack the stack

* @return the stack L

*/

private static StackL<Integer> inverseStack(StackL<Integer> stack) {

StackL<Integer> copiedStack = stack;

StackL<Integer> tmpStack = new StackL<Integer>();

while (!copiedStack.isEmpty()) {

int tmp = copiedStack.pop();

while (!tmpStack.isEmpty() && tmpStack.peekFirst() > tmp) {

copiedStack.push(tmpStack.pop());

}

tmpStack.push(tmp);

}

return tmpStack;

}

/**

* Peek highest element.

*

* @param stack the stack

*/

private static void peekHighestElement(StackL<Integer> stack) {

StackL<Integer> sortedStack = inverseStack(stack);

System.out.println("Highest element: " + sortedStack.peekFirst());

}

/**

* Peek lowest element.

*

* @param stack the stack

*/

private static void peekLowestElement(StackL<Integer> stack) {

StackL<Integer> sortedStack = inverseStack(stack);

System.out.println("Lowest element: " + sortedStack.peekLast());

}

/**

* Prints the second element of stack.

*

* @param stack the stack

*/

private static void printSecondElementOfStack(StackL<Integer> stack) {

int index = 1;

while (stack.hasNext()) {

int value = stack.next();

if (index == 2) {

System.out.println("Second value of stack is " + value);

break;

}

index++;

}

}

/**

* Count number of larger elemets.

*

* @param stack the stack

* @param searchElement the search element

*/

private static void countNumberOfLargerElemets(StackL<Integer> stack, int searchElement) {

int count = 0;

while (stack.hasNext()) {

int value = stack.next();

if (value > searchElement) {

count++;

}

}

System.out.println("Number of element larger than " + searchElement + " is " + count);

}

/**

* Find value.

*

* @param stack the stack

* @param searchElement the search element

*/

private static void findValue(StackL<Integer> stack, int searchElement) {

while (stack.hasNext()) {

int value = stack.next();

if (searchElement == value) {

System.out.println("Value found");

}

}

}

/**

* Generate random number.

*

* @param stack the stack

* @param low the low

* @param high the high

* @param size the size

*/

private static void generateRandomNumber(StackL<Integer> stack, int low, int high, int size) {

Random rand = new Random();

while (size > 0) {

int num = rand.nextInt(60 - 20) + low;

stack.push(num);

size--;

}

}

/**

* Prints the ten elements.

*

* @param stack the stack

*/

private static void printTenElements(StackL<Integer> stack) {

int limit = 10;

StackL<Integer> copiedStack = stack;

while (copiedStack.hasNext()) {

if (limit != 0 && limit <= 10) {

System.out.print(copiedStack.next() + " ");

limit--;

}

else {

System.out.println();

limit = 10;

}

}

}

/**

* Prints the size of stack.

*

* @param stack the stack

*/

private static void printSizeOfStack(StackL<Integer> stack) {

System.out.println("Size of stack is " + stack.size());

}

}

output:

Add a comment
Know the answer?
Add Answer to:
Create a Stack class based on java.util.LinkedList class. Your Stack class should have a push(), pop(),...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • using: class MyQueue<T> { private java.util.LinkedList<T> list; public MyQueue() { list = new java.util.LinkedList<T>(); } public...

    using: class MyQueue<T> { private java.util.LinkedList<T> list; public MyQueue() { list = new java.util.LinkedList<T>(); } public void enqueue(T data) { list.add(data); } public T dequeue() { return list.remove(0); } public T peek() { return list.get(0); } public int size() { return list.size(); } public boolean isEmpty() { return list.isEmpty(); } } class MyQueueTest { public static void main(String[] args) { MyQueue<Integer> queue = new MyQueue<Integer>(); queue.enqueue(3); queue.enqueue(2); queue.enqueue(7); queue.enqueue(1); while (!queue.isEmpty()) { System.out.println(queue.dequeue()); } } } please solve the following:...

  • ) Consider Java's Stack class, and its five standard stack operations: push, pop, peek, isEmpty, and...

    ) Consider Java's Stack class, and its five standard stack operations: push, pop, peek, isEmpty, and clear. Complete the two unfinished methods. Do not modify any other parts of the class.               // Looks at the top two elements of the stack, and removes and returns the larger        // of the two elements from the stack, returning the other element to the stack.        // For example, if the stack, from the top, is 8 10 7 2...

  • C++ Create an array-based implementation of a stack. Each element of the stack should store a...

    C++ Create an array-based implementation of a stack. Each element of the stack should store a string. The stack class should include 3 private member variables (maximum stack size, top of the stack index, and a pointer to the array that holds the stack elements). Public member methods should include a constructor (with an argument of stack maximum size that is used to create a dynamic array), a destructor (that deletes the dynamic array), a push method (argument is a...

  • On java create the following: please solve it complete or don't since it considered as part...

    On java create the following: please solve it complete or don't since it considered as part of problem 1 not even the whole question. The main method that does: Create 2 stacks s1 and s2 Insert 23 integers between 20 and 60 (do not insert duplicates) into s1 Insert 35 integers between 10 and 80 (do not insert duplicates) into s2. Give the user the choice which methods (2-7) to call and option to exit LinkedList<Integer> LL = new LinkedList<Integer>)...

  • Create a flowchart to represent the Push and Pop operations for a Stack based on a linked list data structure. Create a flowchart to represent the Enqueue and Dequeue operations for a Queue based on a...

    Create a flowchart to represent the Push and Pop operations for a Stack based on a linked list data structure. Create a flowchart to represent the Enqueue and Dequeue operations for a Queue based on a linked list data structure. Write the required Java code to implement either a Stack or a Queue data structure based on a linked list. The code should include the class constructors, the necessary properties, and methods to add and remove elements from the data...

  • Write a program that uses a stack to reverse its inputs. Your stack must be generic...

    Write a program that uses a stack to reverse its inputs. Your stack must be generic and you must demonstrate that it accepts both String and Integer types. Your stack must implement the following methods: push, pop, isEmpty (returns true if the stack is empty and false otherwise), and size (returns an integer value for the number of items in the stack). You may use either an ArrayList or a LinkedList to implement your stack. Also, your pop method must...

  • I need to implement raw array Stack for create empty stack, isEmpty, isFull, push, pop, and...

    I need to implement raw array Stack for create empty stack, isEmpty, isFull, push, pop, and size using below pseudo code. I need two classes with stack pseudo code implementation and the main method to demonstrate the correct working of each operation. pseudo code StackADT (using raw array) class StackADT { int top int items[] int max StackADT(int n) Initialize array to n capacity top = 0 max = n boolean isEmpty() if array has no elements return true else...

  • » Part A: Stack Create a Stack struct that is a wrapper for your linked list o You should impleme...

    Using C Please comment » Part A: Stack Create a Stack struct that is a wrapper for your linked list o You should implement the following functions that take a stack o void push(Stack * stack, int value) ● int pop(Stack * stack) Prompt the user to input 5 integers, and use the stack to reverse the integers Print the result to the screen. o o » Part B: Queue o Create a Queue struct that is a wrapper for...

  • Please write a Java interface for an integer stack (should have the methods push, pop, toString)....

    Please write a Java interface for an integer stack (should have the methods push, pop, toString). Then implement this interface using one of our linked list nodes. Then please write an interface for an integer queue ( should have methods enqueue, dequeue, and toString). Then implement this interface using one of our linked list objects. Please see chapter 3 in the text for a definition of a stack. Please write a program that asks the user for how many numbers...

  • Part I: Create a program class named TestArrays This class should have a main() method that...

    Part I: Create a program class named TestArrays This class should have a main() method that behaves as follows: Create an integer array of size 10. Using a loop, fill the elements with increments of 5, starting with 5 in the first element. Using the array elements, sum the second, fifth and seventh elements. Display the sum with a label. Change the fourth element to 86. Subtract 9 from the ninth element. Using a loop, display the elements of the...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT