In: Computer Science
To write a Generic Collection class for Stack<E>, using the generic Node<E> from Lab 5, and test it using a stack of Car, Integer, and String
Stack<E>
For Programming Lab 6, you are to write your own Generic Collection for a Stack that will use your Node<E> from Lab 5
UML for Stack<E>
Stack<E> |
- top : Node<E> |
+ Stack( ) |
Here is an additional description of what your stack should contain/how it should perform:
private fields:
- top which points to a
Node<E>
- numElements an int
a no-arg Constructor:
- sets top to null
- numElements to 0
push(receives element of type E)
- adds a new node to top of
stack
- adds 1 to numElements
pop( ) returns a value of type E
- removes node from top of stack
- decrements numElements by 1
- <<unless the stack is empty-throw EmptyStack exception (provided in Canvas)>>
size( ) returns an int
returns value of numElements
Stack<E> (Stack.java):
Item |
Comment with name (2 points) |
Comment each method / constructor in javadoc format (8 points) |
2 private Fields created as requested |
No-arg Constructor |
push() method adds element of type E to stack and increases numElements (15 points) |
pop() method |
size() method |
following the naming guidelines for Classes and identifiers (8 points) |
proper indenting (methods indented inside class, statements indented inside method, conditionally executed code indented) (8 points) |
organization of your Class( instance variables up top / Constructor / setters/getters ) (8 points) |
Lab must compile and run in order to receive any credit |
import java.util.Scanner;
public class DriverClass
{
public static void main(String[] args)
{
Scanner in = new
Scanner(System.in);
Stack stack = new
Stack();
int data;
while(true)
{
System.out.println("1.Push\n2.pop\n3.size\n4.exit\nEnter
choice::");
int choice =
in.nextInt();
switch(choice){
case 1: System.out.println("Enter
element:\t");
data=
in.nextInt();
stack.push(data);
break;
case 2: System.out.println("Popped Element:\t"+
stack.pop());
break;
case 3: System.out.println("Size of
Stack:\t"+stack.size());
break;
case 4: System.exit(1);
}
}
}
}
////////////:::::::: Stack class
import java.util.NoSuchElementException;
public class Stack
{
private Node top;
private int count;
class Node
{
public int data;
public Node next;
}
// Constructs an empty stack:
public Stack()
{
top = null;
count =0;
}
/**
*Push operation:::::
* Adds an element to the top of the stack
* @param e int to top of stack.
*/
public void push(int e)
{
Node newNode = new
Node();
newNode.data = e;
newNode.next = top;
top = newNode;
count++;
}
/**
* Pop Operation::::
* Removes the element from the top of the stack
* @return the removed String
* If stack empty throw NoSuchElementException
*/
public int pop()
{
if (top == null) {throw new
NoSuchElementException();}
int e = top.data;
top = top.next;
count--;
return e;
}
public int size()
{
return count;
}
}
Outputss:::::