How can I pop, peek and get the size? - java

I have this piece of code where I am actually pushing element into the stack and I did make it but if I want to pop, peek and get the size of the stack afterwards how it should be actually done? Anyone who can provide help I can say thanks a lot for your time.
public class MyGenericsStack<T extends Object> {
private int stackSize;
private T[] stackArr;
private int top;
#SuppressWarnings("unchecked")
public MyGenericsStack(int size) {
this.stackSize = size;
this.stackArr = (T[]) new Object[stackSize];
this.top = -1;
}
public void push(T entry){
if(this.isStackFull()){
System.out.println(("Stack is full. It is increased now"));
this.increaseStackCapacity();
}
System.out.println("Add it: "+entry);
this.stackArr[++top] = entry;
}
public T pop() throws Exception {
if(this.isStackEmpty()){
throw new Exception("Stack is empty. You can't remove element.");
}
T entry = this.stackArr[top--];
System.out.println("Removed: "+entry);
return entry;
}
public T peek() {
return stackArr[top];
}
private void increaseStackCapacity(){
#SuppressWarnings("unchecked")
T[] newStack = (T[]) new Object[this.stackSize*2];
for(int i=0;i<stackSize;i++){
newStack[i] = this.stackArr[i];
}
this.stackArr = newStack;
this.stackSize = this.stackSize*2;
}
public boolean isStackEmpty() {
return (top == -1);
}
public boolean isStackFull() {
return (top == stackSize - 1);
}
public static void main(String a[]){
MyGenericsStack<String> Stack = new MyGenericsStack<String>(4);
Stack.push("kkk");
Stack.push("sss");
Stack.push("ppp");
Stack.push("aaa");
}
}

I'm not sure what you think is wrong with your pop abd peek methods, they look fine to me.
To get the size, you can write a method returning this.top + 1 - this.top holds the last index in the array that was filled, so adding 1 to it will give you the amount of elements stored in the internal array.
public int size() {
return this.top + 1;
}

Related

Failing J-unit test for Shallow Copy on a Linked Stack

I am trying to implement a shallow copy for a Linked Stack, but I am failing the J-unit test provided by my instructor.
I have tried to implement a for loop that will cycle through the stack top to bottom and create a reference for each node to the new list on the pass through. I've added a print statement and the data references seem to match up,but my test are still failing.
public class LinkedStack<E> implements Stack<E>{
private int size = 0;
// Unlike the book, we'll use an inner class for our Node.
// Its two data members can be accessed directly by the Stack
// code, so we don't need setters and getters.
protected class Node{
E data;
Node next;
}
protected Node top; // not public, but can still be seen by other classes in the
// csci211 package.
/** Create an empty stack.
*
*/
public LinkedStack(){
top = null;
}
#Override // see interface for comments.
public void push(E e){
//TODO 75
Node temp = new Node();
temp.data = e;
temp.next = top;
top = temp;
}
#Override // see interface for comments.
public E pop(){
if (top==null) {
throw new NoSuchElementException("Cannout pop an Empty Stack.");
}
E topvar;
topvar = top.data;
top = top.next;
return topvar;
}
#Override // see interface for comments.
public E peek() {
if (top == null) {
throw new NoSuchElementException("Cannout peek an Empty Stack.");
}
//E topvar;
//topvar = top.data;
return top.data;
}
/** Retrieve the number of elements on this stack.
*
* #return an int containing the number of elements
*/
public int size() {
return this.size;
}
/** An Iterator for our LinkedStack.
*
* #author rhodes
*
*/
class LinkedStackIterator implements Iterator<E> {
LinkedStack<E>.Node next; // the book calls this "current"
public LinkedStackIterator(LinkedStack<E> s){
next = s.top;
}
#Override
public boolean hasNext() {
return top != null;
//TODO 100
//return false;
}
#Override
public E next() {
if (!hasNext()) throw new NoSuchElementException();
E data = top.data;
top = top.next;
return data;
//TODO 100
//return null;
}
}
#Override
public void add(E element) {
push(element);
}
#Override
public void clear() {
this.top = null;
this.size = 0;
}
#Override
public List<E> shallowCopy() {
LinkedStack<E> newstack = new LinkedStack<E>();
ArrayList<E> Alist = new ArrayList<E>();
//Iterate through while we haven't hit the end of the stack
Node newtest = top;
while (newtest != null) {
Alist.add(newtest.data);
newtest = newtest.next;
//TODO 85
}
for(int i = Alist.size()-1;i>=0;i--) {
newstack.push(Alist.get(i));
}
return newstack;
}
#Override
public Iterator<E> iterator() {
return new LinkedStackIterator(this);
}
}
This is the Junit tests that I am failing
#Test
#SuppressWarnings("deprecation") // for Date.setHours(), Date.getHours()
public void shallowCopy1() {
// let's use Date, since it's mutable.
LinkedStack<Date> s = new LinkedStack<Date>();
Date d = new Date();
d.setHours(17);
s.push(d);
LinkedStack<Date> s2 =(LinkedStack<Date>) s.shallowCopy();
Date d2=s2.pop();
// The shallow copy should contain references to the same objects
// as the original.
assertTrue(d == d2);
// So, we can change the Date in the original list using the Date that
// came from the shallow copy.
d2.setHours(14);
assertTrue(d.getHours() == 14);
// I don't usually put two asserts in one test, but this seems like
// an instructive example.
}
#Test(expected=NoSuchElementException.class)
public void shallowCopy2() {
LinkedStack<Integer> s1 = new LinkedStack<Integer>();
for(int i=0; i<10; i++) {
s1.push(i);
}
LinkedStack<Integer> s2 =(LinkedStack<Integer>) s1.shallowCopy();
s2.push(10); // supposed to only affect s2
s2.push(11); // supposed to only affect s2
for(int i=0; i<10; i++) {
s1.pop();
}
int last = s1.pop(); // should throw
}
#Test
public void shallowCopy3() {
LinkedStack<Integer> q1 = new LinkedStack<Integer>();
for(int i=0; i<10; i++) {
q1.push(i);
}
LinkedStack<Integer> q2 =(LinkedStack<Integer>) q1.shallowCopy();
//Let's check that the order of elements is correct in the copy.
for(int i=0; i<10; i++) {
int v1=q1.pop();
int v2=q2.pop();
assertEquals(v1, v2);
}
}
If anyone could point me in the right direction I would appreciate it. This is a Homework Problem.
Shallow copies duplicate as little as possible. A shallow copy of a collection is a copy of the collection structure, not the elements. With a shallow copy, two collections now share the individual elements.
Deep copies duplicate everything. A deep copy of a collection is two collections with all of the elements in the original collection duplicated.
protected class Node{
E data;
Node next;
Node(Node node){
this.next = node.next;
this.data = node.data;
}
}
#Override
public List<E> shallowCopy() {
// LinkedStack<E> newStack = new LinkedStack<E>();
//Iterate through while we haven't hit the end of the stack
Node s = new Node(top);
while (top.next != null) {
s.next = new Node(top.next);
top = top.next;
s = s.next;
}
System.out.println("FINSHED!");
return (List<E>) s;
}
#Override
public List<E> shallowCopyWithoutUpdatingNodeClass() {
// LinkedStack<E> newStack = new LinkedStack<E>();
//Iterate through while we haven't hit the end of the stack
Node s = new Node(top);
while (top.next != null) {
s.next = new Node();
s.next.next = top.next;
s.next.data = top.data;
top = top.next;
s = s.next;
}
System.out.println("FINSHED!");
return (List<E>) s;
}
Answer Inspired by :- What is the difference between a deep copy and a shallow copy?
The original problem was the node data was just being overwritten not creating a new node. Then the stack was backwards. Finally I implement and array to reverse the stack.
#Override
public List<E> shallowCopy() {
LinkedStack<E> newstack = new LinkedStack<E>();
ArrayList<E> Alist = new ArrayList<E>();
//Iterate through while we haven't hit the end of the stack
Node newtest = top;
while (newtest != null) {
Alist.add(newtest.data);
newtest = newtest.next;
//TODO 85
}
for(int i = Alist.size()-1;i>=0;i--) {
newstack.push(Alist.get(i));
}
//System.out.println("FINSHED!");
return newstack;
}

Implement two stacks using one array

I still don't know WHERE to implement the second Stack. Am i supposed to make another class? I'm not quite sure how to finish up. I'll keep searching. Any help would be appreciated! I also can't tell if my pop() method is working or not. I printed out the stack.
Output:
true
5
10
15
20
25
30
35
false
public class twoStack {
int maxSize = 10;
int top;
int top2;
int arr[];
public twoStack(int x)
{
maxSize = x;
arr = new int[maxSize];
top = 0;
top2 = maxSize;
}
//push pop empty peek
public boolean empty()
{
if(top == 0)
{
return true;
}
else
{
return false;
}
}
public boolean empty2()
{
if(top2 == maxSize)
{
return true;
}
else
{
return false;
}
}
public void push(int x)
{
if (top<maxSize)
{
arr[top] = 10;
top++;
}
else
{
System.out.print("Stack overflow");
}
}
public void push2(int x)
{
if(top2<0)
{
arr[top2] = 0;
top2--;
}
else
{
System.out.print("Stack Overflow");
}
}
#SuppressWarnings("null")
public Object pop()
{
if(!this.empty())
{
int temp = (int) this.peek();
arr[top-1]=(Integer) null ;
top--;
return temp;
}
else
{
return null;
}
}
#SuppressWarnings("null")
public Object pop2()
{
if(!this.empty2())
{
int temp = (int) this.peek();
arr[top+1]=(Integer) null;
top++;
return temp;
}
else
{
return null;
}
}
public Object peek()
{
if (!this.empty())
{
return arr[top-1];
}
else
{
return null;
}
}
public Object peek2()
{
if(!this.empty2())
{
return arr[top+1];
}
else
{
return null;
}
}
}
//mainstack
package twoStack;
import java.util.Stack;
public class mainStack {
public static void main(String[] args) {
//MM(main method)
Stack<Integer> myStack= new Stack<Integer>();
System.out.println(myStack.empty());
myStack.push(5);
System.out.println(myStack.peek());
myStack.push(10);
System.out.println(myStack.pop());
myStack.push(15);
System.out.println(myStack.peek());
myStack.push(20);
System.out.println(myStack.peek());
myStack.push(25);
System.out.println(myStack.pop());
myStack.push(30);
System.out.println(myStack.peek());
myStack.push(35);
System.out.println(myStack.peek());
myStack.push(40);
System.out.println(myStack.empty());
}
}
If you have one array of maximal size, two stacks are possible: as a stack grows from a fixed position in some direction and shrinks there too. The start position is fixed.
pick a fixed bottom index for both stacks
start the first stack from that bottom index upwards ++
start the second stack from that bottom index downwards --
Use the full unallocated room, that is ++ and -- modulo the array size.
If both stack pointers meet, both stacks are full.
I wonder whether I have told too much. Maybe just that a stack might grow upwards and downwards, and around (modulo), and has a fixed start.
Try this:
public class TwooStacksInAnArray {
int[] array;
int headOne,headTwo;
public TwooStacksInAnArray(int n){
array=new int[n];
headOne=-1;
headTwo=array.length;
}
public void pushX(int data){
if(headTwo-headOne>1)
array[++headOne]=data;
else
System.out.println("No space to fill data on stack1 ");
}
public void pushY(int data){
if(headTwo-headOne>1)
array[--headTwo]=data;
else
System.out.println("No space to fill data on stack2 ");
}
public int popX(){
if(headOne>-1)
return array[headOne--];
else {
System.out.println("underflow stack1");
return 0;
}
}
public int popY(){
if(headTwo<array.length)
return array[headTwo++];
else{
System.out.println("underflow stack2");
return 0;
}
}
public boolean isEmptyX(){
return (headOne==-1);
}
public boolean isEmptyY(){
return (headTwo==(array.length));
}
}
public class stackDriver {
public static void main(String[] args) {
// TODO Auto-generated method stub
TwooStacksInAnArray twostack=new TwooStacksInAnArray(10);
twostack.pushX(10);
twostack.pushY(9);
twostack.pushX(100);
twostack.pushY(99);
System.out.println("Poped element from stack 1: "+twostack.popX());
System.out.println("Poped element from stack 2: "+twostack.popY());
}
}

Java Generic class doesn't display the objects i pass into it

I am trying to build a simple generic class that uses generic objects in java. everything compiles fine, but when i run the code, it doesn't display the objects i passed to it.
Here is my code:
public class ListDriver {
public static void main(String[] args) {
List<String> glist = new List<String>(10);
glist.add("milk");
glist.add("eggs");
System.out.println("Grocery List" + glist.toString());
}
public class List<T> {
private T[] datastore;
private int size;
private int pos;
public List(int numElements) {
size = numElements;
pos = 0;
datastore = (T[]) new Object[size];
}
public void add(T element) {
datastore[pos] = element;
}
public String toString() {
String elements = "";
for (int i = 0; i < pos; ++i) {
elements += datastore[i] + "";
}
return elements;
}
}
}
You don't increment your pos variable, so you're always adding in the same place. Try
public void add(T element) {
datastore[pos++] = element;
}
Your add method always replaces the element in position 0 (zero). You forgot to increment pos (pos++;)

JAVA: Simple pop does only return first item

I got following code set up:
public class ListStack implements Stack {
private class List {
List next;
Object object;
public List(Object o, List n) {
object = o;
next = n;
}
}
private List firstItem;
private int size;
public ListStack() {
firstItem = new List(null, null);
size = 0;
}
public List getEnd() {
List endEl = firstItem;
while (endEl.next != null) {
endEl = endEl.next;
}
return endEl;
}
public boolean push(Object o) {
List e1 = new List(o, null);
this.getEnd().next = e1;
size++;
return true;
}
public Object pop() {
if (this.firstItem.next == null) {
return null;
} else {
List endEl;
List tempEl;
endEl = this.getEnd();
tempEl = firstItem;
while (tempEl.next != endEl) {
tempEl = tempEl.next;
}
tempEl.next = null;
size--;
return tempEl.object;
}
}
public int size() {
return size;
}
public static void main(String[] args) {
Stack s = new ListStack();
Object test = new Object();
Object test2 = new Object();
System.out.println("pushing Object test to List: " + s.push(test));
System.out.println("pushing Object test2 to List: " + s.push(test2));
System.out.println("popping Object from List: " + s.pop());
System.out.println("popping Object from List: " + s.pop());
System.out.println("popping Object from List: " + s.pop());
}
}
And this one:
public interface Stack {
public int size();
public boolean push(Object o);
public Object pop();
}
But its only giving me the first object and twice "null" but it should give me the two objects :( where is my mistake? It is asking for the last item and gives it back (.object) but only returns first object adress
I think what your pop() function should return is endEl.object.
Your code is way too long-winded. A stack is a data structure that can efficiently push and pop elements. But your code has to traverse the whole stack for both operations (i. e. runs in O(n) instead of O(1) time.).
Prepending to your list is much more efficient as appending.
Example for an efficient push:
public void push(Object o) {
firstItem = new List(o, firstItem);
size++;
}

Linked List Stack Loses Last Item Pushed on Stack

I am working on a Linked List implementation of a Stack, and seem to have what I need with only one error. I am inserting 3 strings, but before the 3rd string is popped, I get a NullPointerException.
In running debug I found that this missing value is being 'popped' off this list but it seems like it is not counted...meaning it is missing from the stack, not printed to the console, and the list does one more iteration at which point the NullPointerException is thrown because the last value was already popped. Can someone tell me how to get all of my values to print to console?
Here is my LinkedListStack Class:
public class LinkedListStack <T>{
private LinkedListStackNode<T> top;
public T data;
class LinkedListStackNode<T> {
private T data; //LINE 8
private LinkedListStackNode<T> next;
public LinkedListStackNode(T data, LinkedListStackNode<T> next) {
this.data = data;
this.next = next;
}
}
public void stack(){
top = null;
}
public boolean isEmpty(){
return top == null;
}
public void push (T t){
top = new LinkedListStackNode<T> (t, top);
}
public T pop (){
if (isEmpty()){
System.out.println("The stack is empty!");
}
else{
top = top.next;
}
return top.data; //Line 32
}
public T peek(){
if (isEmpty()){
System.out.println("Stack is Empty");
}
return top.data;
}
}
Here is my Main():
public class StacksAndQsMain {
public static void main(String[] args) {
...snipped code to condense (not part of this implementation)...
//LinkedList Implementation
LinkedListStack<String> lls = new LinkedListStack<>();
String s3 = "Tonight"; //this does not print but is removed from Stack
String s4 = "We Conqure"; //prints fine
String s5 = "Stacks"; //prints fine
lls.push(s5);
lls.push(s4);
lls.push(s3);
while (!lls.isEmpty()){
System.out.println(lls.pop()); //LINE 32
}
}
}
It appears you're popping the top off and then reading the new top's value in the pop() method
It should look like this:
public T pop (){
if (isEmpty()){
throw new RuntimeException("Stack is empty");
}
else{
T ret = top.data;
top = top.next;
return ret;
}
}
While you're at it, you might as well fix your peek()
public T peek(){
if (isEmpty()) {
throw new RuntimeException("Stack is empty");
}
return top.data;
}

Categories