Exercise 4.1 (40 points) Create a stack with some data elements, and finish such
ID: 3912846 • Letter: E
Question
Exercise 4.1 (40 points) Create a stack with some data elements, and finish such operations as initialization, Push, Pop, etc. All operations should be implemented as independent functions, which can be called by the main function. (1) Create a stack by entering some positive integer data elements, and end the process by entering -1, and output all the elements; (2) Get the length of the stack; (3) Delete a data element from the stack, and output the data value. Exercise 4.1 (40 points) Create a stack with some data elements, and finish such operations as initialization, Push, Pop, etc. All operations should be implemented as independent functions, which can be called by the main function. (1) Create a stack by entering some positive integer data elements, and end the process by entering -1, and output all the elements; (2) Get the length of the stack; (3) Delete a data element from the stack, and output the data value. Exercise 4.1 (40 points) Create a stack with some data elements, and finish such operations as initialization, Push, Pop, etc. All operations should be implemented as independent functions, which can be called by the main function. (1) Create a stack by entering some positive integer data elements, and end the process by entering -1, and output all the elements; (2) Get the length of the stack; (3) Delete a data element from the stack, and output the data value.Explanation / Answer
In this code i have implemented the stack using Array List (Dynamic array in java) in java .
import java.util.ArrayList;
import java.util.EmptyStackException;
public class chegg {
public static ArrayList<Integer> arr = new ArrayList<>();
public static void main(String[] args) {
push(1);
System.out.println(arr);
push(3);
System.out.println(arr);
push(5);
System.out.println(arr);
System.out.println("the current size of the stack is" + arr.size());
pop();
System.out.println(arr);
pop();
System.out.println(arr);
System.out.println("the current size of the stack is" + arr.size());
}
public static void mystack (){
arr = new ArrayList<Integer>();
}
public static void push(int value){
arr.add(value);
}
public static void pop(){
if (!isEmpty()){
arr.remove(arr.size() - 1);
}else{
System.out.println("stack underflow");
System.out.println("the current size of the stack is 0");
throw new EmptyStackException();
}
}
public static boolean isEmpty(){
return (arr.size() == 0);
}
public static int peek(){
if (!isEmpty()){
return arr.get(arr.size() - 1);
}else{
System.out.println("no element in stack");
throw new EmptyStackException();
}
}
public String toString(){
System.out.println(arr.toString());
return arr.toString();
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.