Stacks in Java with exceptions - java

Question :
b) A Stack is a last-in first-out (LIFO) data structure. Write a Java class
Stacklnt that stores a stack of integers using an alray as its private data
structure. A Stacklnt has:
A maximum size, which is set when a Stacklnt object is created.
An exception should be thrown if the size is outside the range 10 to .
1000
A method push, to add a value to the top of the stack. An exception
should be thrown if the stack is full when push is called.
A method pop, to remove and return the value at the top of the stack.
An exception should be thrown if the stack is empty when pop is
called.
c) Write some example code to show how your class Stacklnt from part (b)
should be used. Include examples of normal usage and for all cases when
exceptions are thrown.
Ok so basically this is a question im trying to solve and would really really appreciate some help.
exceptions are in this form
// Throw an exception!
public T pop() throws EmptyStackException
{
if (contents.size() == 0)
{ throw new EmptyStackException(); }
else
{ return contents.remove(0); }
}
me so far :
public class Stack {
private int top;
private int[] storage;
Stack(int capacity) {
if (capacity <= 0)
throw new IllegalArgumentException(
"Stack's capacity must be positive");
storage = new int[capacity];
top = -1;
}
void push(int value) {
if (top == storage.length)
throw new StackException("Stack's underlying storage is overflow");
top++;
storage[top] = value;
}
int peek() {
if (top == -1)
throw new StackException("Stack is empty");
return storage[top];
}
}

You're trying to do the whole program at once, which is a bit difficult because there could be many trivial syntax errors, and any ONE of them will cause it to not compile.
So, the recommendation is to take baby steps - you'll probably hear this a lot. It goes like this (assuming you haven't written any code yet):
1) Edit your StackInt.java file so that it only contains the following:
class StackInt {
}
2) Compile it.
2a) If it doesn't compile correctly, fix those errors FIRST before adding new code.
3) Add a small amount of new code. Say, a main() method. Your class now looks like this:
class StackInt {
public static void main(String[] args) {
System.out.println("hello world!");
}
}
4) Compile it. Then run it. If it doesn't compile, fix those errors before continuing. If it compiles, then run it. You should see it print out "hello world!". This tells you it was run successfully. If there's no output, then you know somethings wrong, and you'll have to fix that before continuing.
In this way, you take "baby steps" - you add just a small amount of code each time, and then compile it and run it to make sure it works the way you expect.
Doing programs this way has been really helpful to me. You can work on one method at a time, instead of typing ALL of them in and wondering where it fails. I recommend it.
Edit:
Since you already have code written, you could adapt this "baby steps" approach by commenting out most of your code so that you don't waste it. Use /* and */ to comment out entire sections - this way the compiler ignores it and you can go about trying out one piece at a time. It looks like this:
class StackInt {
/*
this is "commented out"
push(int number) {
}
*/
public static void main(String[] args) {
System.out.println("hello world!");
}
}
Hope this helps.

read Fundamentals of OOP and Data Structures in Java - Richard Wiener
Chapter 11 is all about stacks and queues

As an answer to your last comment to your question: your syntax is not bad. I cleaned your code up a bit and, once you've implemented the StackException class and the pop method, it should compile correct:
public class Stack {
private int top;
private int[] storage;
public Stack(int capacity) {
if (capacity <= 0) {
throw new IllegalArgumentException(
"Stack's capacity must be positive");
}
top = -1;
storage = new int[capacity];
}
public void push(int value) {
if (top == storage.length) {
throw new StackException("Stack's underlying storage is overflow");
}
top++;
storage[top] = value;
}
public int peek() {
if (top == -1) {
throw new StackException("Stack is empty");
}
return storage[top];
}
public int pop() {
// TODO
}
}

Here's what you should do:
Create a class named Stacklnt**.
Use an array of integers int[] as an instance variable.
Use the constructor of the class to initiate the array with a given size as the constructor's parameter. You have to check that this size is in the range (10 to 1000)
make the two instance methods push and pop. You can use an integer variable as a pointer to the current array position, so you increase it when push is called, and you decrease it when pop is called. You have to make sure this pointer doesn't exceed the limits (i.e. doesn't go lower than zero, and doesn't go higher than the size).

Read over your question once more and look for all of the things you have not done.
you have not put in the method pop
you have not followed the example of exceptions given by the sample pop()
you have not check for range properly
you have not written a main method which instantiates a stack and tests it

Related

Am I implementing a heap-based priority queue correctly? Is downheap necessary?

I believe I just correctly completed the following assignment:
Implement a heap ­based priority queue class using the vector representation, containing characters.
My program compiles and when implemented for the remainder of the assignment I achieved all of the desired outputs. My question is whether I actually implemented the heap correctly. My teacher identified three key methods for a heap-based queue: downheap, upheap, and extractMin.
public static void upheap(int j)
{
int p = parent(j);
if(heap.get(j) < heap.get(p)) { swap(j,p); }
if (j == 0) return;
upheap(p);
}
public static char extractRoot()
{
if (heap.size() == 0)
return 0;
char root = heap.get(0);
heap.set(0,heap.get(heap.size() - 1));
heap.remove(heap.size() - 1);
downheap(0);
return root;
}
public static void downheap(int j)
{
if(hasLeft(j))
{
int smallerIndex = left(j);
if(hasRight(j) && heap.get(right(j)) < heap.get(left(j)))
smallerIndex = right(j);
if(heap.get(j) > heap.get(smallerIndex))
{
swap(j, smallerIndex);
}
upheap(j);
downheap(smallerIndex);
}
}
However, I feel like my downheap function is just piggybacking off of upheap, and actually entirely unnecessary. I have the function:
public static void add(char c)
{
heap.add(c);
upheap(heap.size() - 1);
}
(where heap is an ArrayList) and that automatically makes sure that every new entry follows the heap-order property. I never actually end up using downheap to sort anything - so is there any point to even keep it in the class? When would I use it?
If anyone wants to see the rest of the methods in the class I'll post
Actually you can remove the call to upheap() in your downheap() method.
As you know the root in a priority queue heap is highest priority element.
The downheap method comes into picture only when the highest priority element is removed i.e. the root element is swapped with the last element. In your case the extractRoot() method. Once you extractRoot() all the the other elements in the heap would satisfy the heap property except the one on root.
Also when you are moving the root element down you are swapping with the smaller value i.e swap(j, smallerIndex). Hence there would never be a case when you would need to move an element up the heap in case of downheap().
To answer your question, when you call add() downHeap() is useless but when you call extractMin() downheap() is necessary.
Heap Image

Java: Implement stack with one queue, any problems?

So I tried to implement a stack with just one queue and it appears to work, but I'm not sure if there's something wrong with it since most of the solutions I've seen online use two queues. Can anyone tell if me if there are problems with my implementation?
public class MyStack<T> {
/**
* #param args
*/
private Queue<T> q = new LinkedList<T>();
public MyStack(){
}
public static void main(String[] args) {
// TODO Auto-generated method stub
MyStack<String> s = new MyStack<String>();
s.push("1");
s.push("2");
s.push("3");
s.push("4");
System.out.println(s.pop());
System.out.println(s.pop());
System.out.println(s.pop());
System.out.println(s.pop());
System.out.println(s.pop());
}
public void push(T s){
q.offer(s);
}
public T pop(){
int n = q.size();
for(int i = 0; i < n-1; i++){
q.offer(q.poll());
}
return q.poll();
}
}
Output:
4
3
2
1
null
Your solution is inefficient because you have to loop through the whole stack every time you pop something from it. (Effectively you have to traverse the whole linked list, before removing the element that was at the end.)
Edit: Java's linked list is doubly linked anyway, so this is entirely pointless.
You should use either a Stack or a Deque or even a LinkedList.
Implementing your own is just ... pointless. Unless of course (as #bas suggests) you are doing a course on data structures in which case you should go Commando and implement your own structure from scratch. Using another structure because it is nearly like the one you are trying to make is like using a hammer with screws.
If you really need to implement something yourself something like this should work:
public class Stack<T> {
private Entry top = null;
private class Entry {
final Entry up;
final T it;
public Entry(Entry up, T it) {
this.up = up;
this.it = it;
}
}
public void push ( T it ) {
top = new Entry(top, it);
}
public T pop () {
if ( top == null ) {
throw new EmptyStackException();
}
T it = top.it;
top = top.up;
return it;
}
}
NB: This may not be thread safe.
There is absolutely no reason a stack should use two queues. As a matter of fact, it only needs to keep track of one top-node that references the nodes below it.
The code seems to work, but as nachokk said, this is not the site for code review. This site is ment if you run into errors and require assistance.
You must use two queues ONLY when you have basic queues operations, like enqueue and dequeue. When you can use other methods, especially iterating over queue, you can do it with only one queue, like you did.

how do i make a stack out of a linked list? [duplicate]

This question already has answers here:
Closed 10 years ago.
I'm trying to create a Stack to take a string and add each of the strings characters to it, but I was told it would be far more efficient use a LinkedList. How would I use a LinkedList to create and manipulate a stack?
An example would be very appreciated!
Ok, the problem is that you're not using First at all. Try the following:
public class Example
{
private LinkedList aList = new LinkedList();
public void push(char c) {
aList.addFirst(c);
}
public Object pop() {
return aList.removeFirst();
}
public boolean empty() {
return aList.isEmpty();
}
public static void main(String[] args) {
Stack exmpStack = new Stack();
String ranString = "Dad";
for (int i = 0; i < ranString.length(); i++) {
exmpStack.push(ranString.charAt(i));
}
while (!exmpStack.empty()) {
System.out.print(exmpStack.pop());
}
}
}
Because you never use First it's always null - so your loop never runs at all! Instead of using that at all, just use the build in isEmpty() function.
Edit: Of course, you don't really need those functions at all - the following will work fine:
public class Example
{
private LinkedList aList = new LinkedList();
public static void main(String[] args) {
String ranString = "Dad";
for (int i = 0; i < ranString.length(); i++) {
aList.push(ranString.charAt(i));
}
while (!aList.isEmpty()) {
System.out.print(aList.pop());
}
}
}
Now this is still a bit unsafe - you can go one step further by using the following:
private LinkedList<Character> aList = new LinkedList<>();
That way it's a bit safer, and returns Characters instead of Objects - and Characters can be implicitly cast to char :)
Java's LinkedList is a doubly linked list, with efficient accessors to get, add, and remove elements both at the end and at the head of the list, so you can use those methods to emulate a stack.
A LinkedList provides more operations that that of a stack.
You use a stack for pushing and popping your characters of your string. However you can only retrieve the character in the order that opposite the way you insert your string. So are you sure if you want this behaviour.
A linkedlist allows you to add/retrieve your data either from head / tail.
LinkedList is indeed more efficient, as Stack comes with synchronized methods by virtue of its reliance on Vector. In single-threaded applications, using the latter means paying the synchronization price for no benefit. Even in multi-threaded applications, you may want more control over synchronization.
Here's a possible LinkedList based solution. Please note the use of composition instead of inheritance. This will give you a well behaved Stack that cannot be abused by using List-related methods.
class MyStack<T> {
private List<T> list = new LinkedList<T>();
public void push(T object) { list.add(0, object); }
public T pop(T object) {
if (isEmpty()) throw new NoSuchElementException();
return list.remove(0);
}
public boolean isEmpty() { return list.isEmpty(); }
}
Nonetheless, if your stack is meant only for string characters as your question suggests, you might want to emulate a stack directly on a dynamic character array. I will leave that as an exercise to the reader, or I may provide it in a future edit.
Here is the sample: Stack implementation. Hope it helps.
It is done with C# but you get the idea

Return the stack element at a given index without modifying the original Stack in Java

Ok I was recently asked this in an interview, and I am intrigued. Basically I have a stack with a certain set of values, I want to pass the stack object in a function and return the value at certain index. The catch here is that after the function is complete, I need the stack unmodified; which is tricky because Java passes reference by value for objects. I am curious if there is purely a java way to do using push(), pop(), peek(), isempty() and primitive data type. I am against copying the elements into an array or string. Currently the cleanest I have got is using clone, find the code below:
import java.util.Stack;
public class helloWorld {
public int getStackElement( Stack<Integer> stack, int index ){
int foundValue=null;//save the value that needs to be returned
int position=0; //counter to match the index
Stack<Integer> altStack = (Stack<Integer>) stack.clone();//the clone of the original stack
while(position<index)
{
System.out.println(altStack.pop());
position++;
}
foundValue=altStack.peek();
return foundValue;
}
public static void main(String args[]){
Stack<Integer> stack = new Stack<Integer>();
stack.push(10);
stack.push(20);
stack.push(30);
stack.push(40);
stack.push(50);
stack.push(60);
helloWorld obj= new helloWorld();
System.out.println("value is-"+obj.getStackElement(stack,4));
System.out.println("stack is "+stack);
}
}
I understand that cloning is also copying, but that's the basic flaw I am aiming to remove. Stripped down I am asking if I would be actually be able to pass the stack's value instead of passing the value of its reference.
Thanks in advance.
int position =5;
Integer result = stack.get(position);
Java Doc here
If you cannot use another stack, you can cheat and abuse a local variable on the call stack for the same purpose by making a recursive method:
public static <T> T getStackElement(Stack<T> stack, int index) {
if (index == 0) {
return stack.peek();
}
T x = stack.pop();
try {
return getStackElement(stack, index - 1);
} finally {
stack.push(x);
}
}

returning middle element in stack

I have to create a method peek MidElement , so as return the middle element of the stack .
So do I have to use an ArrayList, or TORTOISE-HARE algo .
The following is my Class , which has a method named peekMidElement.
How do I reference Size() to the ArrayList .
When I compile the following , I am getting IndexOutOFBoundsExcption at ArrayList.RangeCheck(UnknownSource) & at ArrayList.get(UnknownSource)
public class SortableStack<E extends Comparable<E>> implements ISortableStack<E> {
private int N;
private Node first;
private ArrayList<E> listOne = new ArrayList<E>();
/* I have to reference the Stack to array list
which I am going use for finding the size of the stack */
public boolean isEmpty() {
return first == null;
}
public int size() {
return N;
}
public E peekMidElement() {
if(listOne.size() <= 0){
throw new EmptyStackException();
}
return listOne.get(listOne.size()/2);
}
I cannot see how the code snippet you gave can throw an IndexOutOfBoundsExcption at the point you have indicated. I conclude that:
the code snippet is not the actual code (e.g. it has been spliced together from a larger class, leaving out some crucial details), or
the exception is not thrown at the place you indicated, or
... this class (which is not thread-safe) is being used in a multi-threaded application without adequate synchronization. The scenario is that some other thread deletes a bunch of elements from listOne at exactly the wrong moment. This unlikely, and if it was the cause, the failure would only occur very occasionally.

Categories

Resources