public void push(E e)
{
list.add(e);
}
public E pop()
{
list.remove(list.size()-1);
}
public E peek()
{
}
public boolean empty()
{
if ( list.size()== 0)
{
return false;
}
else
{
return true;
}
}
This is part of a driver code my teacher gave me in order to under stand the stack. I understand what each part of the stack does, I am just not understanding how to implement the stack based on this code. I need help with the peek method mainly, but if you see other issues please let me know. I would appreciate the help.
public E peek(){
if(empty()) return null;
int top = list.size()-1;
return list.get(top);
}
AND empty method can be simplifized to:
public boolean empty(){
return list.size() == 0;
}
OR
public boolean empty(){
return list.isEmpty();
}
AND pop method should throws NoSuchElementException when stack is empty.
public E pop(){
if(empty()) throw new NoSuchElementException();
int top = list.size()-1;
return list.remove(top);
}
Related
I'm new here and I have a problem.
I'm trying to implement a Comparator to compare two stacks by top.
The code looks like this
class Comp implements Comparator<Stack<Integer>> {
#Override
public int compare(Stack<Integer> st1,Stack <Integer> st2) {
return st1.peek()-st2.peek();
}
}
I got java.util.EmptyStackException at st1.peek()-st2.peek(); and I don't know why. Maybe you will help me with better implementation for my problem. Thanks!
Stack.peek throws EmptyStackException when the stack is empty.
You need to check if the stack is empty before calling peek on it,
for example, if you want the empty stacks to come before non-empty ones:
#Override
public int compare(Stack<Integer> st1, Stack<Integer> st2) {
if (st1.isEmpty() && st2.isEmpty()) {
return 0;
}
if (st1.isEmpty()) {
return -1;
}
if (st2.isEmpty()) {
return 1;
}
return st1.peek() - st2.peek();
}
Or if you want the empty stacks to come after the non-empty ones:
#Override
public int compare(Stack<Integer> st1, Stack<Integer> st2) {
if (st1.isEmpty() && st2.isEmpty()) {
return 0;
}
if (st1.isEmpty()) {
return 1;
}
if (st2.isEmpty()) {
return -1;
}
return st1.peek() - st2.peek();
}
I'm trying to teach myself some java and im stuck on a problem that seems kind of easy but i still don't seem to find a solution.
What I have so far:
Interface:
public interface ADTStack<T> {
public boolean isEmpty();
public void push(T element);
public T top() throws IllegalStateException;
public void pop() throws IllegalStateException;
}
Class Stack:
public class Stack<T> implements ADTStack<T> {
private java.util.LinkedList<T> data;
public Stack() {
data = new java.util.LinkedList<T>();
}
#Override
public boolean isEmpty() {
return data.isEmpty();
}
#Override
public void push(T element) {
data.add(0, element);
}
#Override
public T top() throws IllegalStateException {
if (isEmpty()) {
throw new IllegalStateException("Stack is emtpy.");
}
return data.getFirst();
}
#Override
public void pop() throws IllegalStateException {
if (isEmpty()) {
throw new IllegalStateException("Stack is empty.");
}
data.remove(0);
}
Alright , so here is what I'm trying to do.
I'm trying to write a methode equals to compare two Stacks.
My idea was to use a third Stack to be able to bring both stacks into
their original state after comparing them.
Here's what I have:
Stack supportStack = new Stack();
public boolean equals(ADTStack<T> s){
if (data.isEmpty() != s.isEmpty()){
return false;
}
if (data.isEmpty() && s.isEmpty()){
return true;
}
T element_a = this.top();
T element_b = s.top();
if( (element_a ==null && (element_b !=null) || !element_a.equals(element_b) || element_a != null && element_b == null)){
return false;
}
data.pop();
s.pop();
supportStack.push(element_a);
boolean result = data.equals(s);
while (!supportStack.isEmpty()){
data.push(supportStack.top());
s.push(supportStack.top());
supportStack.pop();
}
return result;
}
I get a lot of errors when I compile the code and it seems that something is wrong with :
Stack supportStack = new Stack();
I don't really know what's wrong and how to solve the error. I made a runner-class and I tried the constructor and it worked so I'm confused at what's wrong.
public class Runner {
public static void main(String[] args){
Stack test = new Stack();
test.push(12);
System.out.println(test.top());
}
}
I gladly take any advice or constructive criticism since I'm teaching myself and if anything seems unclear feel free to ask.
Stack supportStack = new Stack();
Stack is called a raw type: it's like not using generics. You need to use:
Stack<T> supportStack = new Stack<T>();
But, as a hint: you don't need to do this. You can just do:
return this.data.equals( s.data );
.. and by repeated, I mean repeated. I have a simple implementation of a list interface, functioning like a simple baby-version of the LinkedList.
I have the classes "Knoten"(means "knot" in German), MyLinkedList and, well, Main.
The Error my compiler tosses at me originates in class Knoten, line 35.
But it doesn´t tell me what kind of error it is.
"at Knoten.nextN(Knoten.java:35)"
is all it says. A million times. My whole cmd window is filled with this line. I bet it printed this error message for more than hundred times, again and again. I tried to search for similar problems, but couldn´t really find anything useful because I don´t know which error to search for.
Why did my program crash?
Please help..
Knoten:
class Knoten<T> {
Knoten nachfolger;
T t;
public Knoten(T t){
this.t = t;
nachfolger = null;
}
public void add(T tneu) {
if (nachfolger != null) {
nachfolger.add(tneu);
}
else {
Knoten kneu = new Knoten(tneu);
nachfolger = kneu;
}
}
public Knoten giveNachfolger(){
return nachfolger;
}
public T fuerIDGeben(int index, Knoten anfang) {
if(index == nextN(anfang)){
return (T) nachfolger.t;
}
return null;
}
private int nextN(Knoten k){
int i = 1;
if (nachfolger != null){
i = i+1;
nextN(nachfolger);
} else {}
return i;
} }
MyLinkedList:
class MyLinkedList<T> implements MyList<T>{
Knoten anfang;
public MyLinkedList<T>(){
anfang = null;
}
public T get(int index){
return (T) anfang.fuerIDGeben(index, anfang);
}
public void add(T t){
if(anfang != null){
anfang.add(t);
} else {
Knoten newKnoten = new Knoten(t);
anfang = newKnoten;
}
}
public MyIterator<T> iterate(){
return new MyLinkedIterator<T>();
}
private class MyLinkedIterator<T> implements MyIterator<T>{
public boolean hasNext(){
if(anfang.giveNachfolger() != null){
return true;
}
return false;
}
public T next(){
if(anfang.giveNachfolger() != null){
return (T) anfang.giveNachfolger().t;
}
return null;
}}}
import java.util.*;
And Main:
class Main{
public static void main(String[] args){
MyList<Integer> list = new MyLinkedList<Integer>();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
list.add(5);
System.out.println(list.get(0));
MyIterator<Integer> it = list.iterate();
while(it.hasNext()){
System.out.println(it.next());
}
}}
You have infinite recursion in nextN(), leading to a stack overflow.
If you look closely at the implementation of nextN(), it repeatedly calls itself with the same argument. This continues until the JVM runs out of stack, at which point you get a StackOverflowError. The stack trace at the point of the exception will mention nextN() many times.
Since you are not using k in the nextN function, it always calls itself with the same parameter and brings infinite loops.
Instead of that, you should call the nextN function with the member variable of k in order to iterate over them.
If you have a link like:
k -> k.nachfolger -> k.nachfolger.nachfolger -> ...
Then you need to change your function with this:
private int nextN(Knoten k){
if (k.nachfolger != null){
return nextN(k.nachfolger) + 1;
}
return 1;
}
I am trying to write a program that checks for parentheses matching using stacks.This is my ArrayStack class.
public class ArrayStack{
private final int DEFAULT_SIZE=10;
public int tos;
Object[] array;
public ArrayStack(){
array =new Object[DEFAULT_SIZE];
tos=-1;
}
public void push(Object e)throws OverFlowException{
if (isFull()){
throw new OverFlowException("OverFlow");
}
else{
array[tos+1]=e;
tos++;
}
}
public Object topAndpop() throws EmptyStackException{
Object returnPop;
if (isEmpty())
throw new EmptyStackException("Stack empty");
else{
returnPop=top();
pop();
}
return returnPop;
}
public void pop() throws EmptyStackException{
if (isEmpty())
throw new EmptyStackException("Stack empty");
else
tos--;
}
public Object top() throws EmptyStackException{
if (isEmpty())
throw new EmptyStackException("Stack empty");
else
return array[tos];
}
public boolean isEmpty(){
return tos==-1;
}
public boolean isFull(){
if(tos==array.length)
return true;
else
return false;
}
public void makeEmpty() throws EmptyStackException{
while (tos>=0){
if (isEmpty())
throw new EmptyStackException("Stack empty");
else
pop();
}
}
public void print(){
for (int i=0;i<=tos;i++){
System.out.println(array[i]);
}
}
public static void main (String args[]) throws EmptyStackException,OverFlowException {
ArrayStack newStack=new ArrayStack();
newStack.push("S");
newStack.push("apple");
newStack.push("D");
newStack.topAndpop();
newStack.push("P");
newStack.print();
}
}
And this is my matching class.
public class Matching{
ArrayStack match_Stack=new ArrayStack();
Object popped;
Object[] array_match={"{","}"};
public boolean matching() {
for(int i=0;i< array_match.length;i++){
if (array_match[i]=="{" || array_match[i]=="[" ||array_match[i]=="(" )
match_Stack.push(array_match[i]);
if(array_match[i]=="}" || array_match[i]=="]" || array_match[i]==")"){
if (match_Stack.isEmpty())
return false;
if (match_Stack.topAndpop()==array_match[i]);
return true;
}
}
if (match_Stack.isEmpty())
return true;
else
return false;
}
public static void main (String args[]) throws EmptyStackException,OverFlowException {
}
}
This is EmptyStackException class :
public class EmptyStackException extends Exception{
public EmptyStackException(){
super();
}
public EmptyStackException(String s){
super(s);
}
public void print(){
System.out.println("OverFlow");
}
}
But the problem is when I compile matching I get an error as unreported exception EmptyStackException.must be caught or declared to be thrown.
I think the problem is with exceptions which I don't have a good knowledge of.I am stuck here for days and because of this exception issue I am unable to study the rest of data structures. So any help on how I can fix this and run this would be greatly helpful.
You really should read a tutorial about exceptions and work it through completely. This way you will get a better understanding of exceptions.
Your problem is the method Matching.matching(). You are using the methods ArrayStack.push(Object) and ArrayStack.topAndpop() in the method's implementation. But these methods are declared to (potentially) throw an EmptyStackException.
Your matching method does not deal with that exception. The exception must be either caught or thrown. This is what the compiler does tell you. So for a first coming-through declare the method as
public boolean matching() throws EmptyStackException
I am trying to implement the stack i.e., DSAStack.java using my linked list i.e., DSALinkedList.java
How do I do it? I think I am supposed to have push() perform an insertFirst() and pop() do a peekFirst() and removeFirst() to get the LIFO behaviour? and what about isEmpty()
and the other methods?
I am not sure, please help me out. A clear explanation with a code would be much appreciable. Thank you in advance!
Here is the DSAStack.java
public class DSAStack implements Iterable {
public static int DEFAULT_CAPACITY = 100;
private DSALinkedList list;
private int count;
private Object[] stack;
public DSAStack() {
count = 0;
stack = new Object[DEFAULT_CAPACITY];
}
public DSAStack(int maxCapacity) {
count = 0;
stack = new Object[maxCapacity];
}
public int getCount() {
return count;
}
public boolean isEmpty() {
boolean empty = (count == 0);
return empty;
}
public boolean isFull() {
boolean full = (count == stack.length);
return full;
}
public void push(Object value) {
if (isFull())
throw new IllegalArgumentException("Stack is full");
else
stack[count] = value;
count++;
}
public Object pop() {
Object topVal = top();
count--;
return topVal;
}
public Object top() {
Object topVal;
if (isEmpty())
throw new IllegalArgumentException("Stack is empty");
else
topVal = stack[count-1];
return topVal;
}
public Iterator iterator() {
return list.iterator();
}
}
AND here is the DSALinkedList.java
import java.util.*;
public class DSALinkedList {
public DSAListNode head;
public DSAListNode tail;
Object[] newValue;
public DSALinkedList() {
head = null;
tail = null;
}
public void insertFirst(Object newValue){
DSAListNode newNd;
newNd = new DSAListNode(newValue);
if (head == null) {
head = newNd;
tail = newNd;
} else {
newNd.setNext(head);
head = newNd;
}
}
public void insertLast(Object newValue){
DSAListNode newNd;
newNd = new DSAListNode(newValue);
if(head == null){
head = newNd;
} else {
tail.next = newNd;
tail = newNd;
}
}
public boolean isEmpty() {
return (head == null);
}
public Object peekFirst(){
Object nodeValue;
if (head == null)
throw new IllegalArgumentException("head is empty");
else
nodeValue = head.getValue();
return nodeValue;
}
public Object peekLast(){
Object nodeValue;
if (head == null)
throw new IllegalArgumentException("head is empty");
else
nodeValue = tail.getValue();
return nodeValue;
}
public Object removeFirst(){
Object nodeValue;
if (head == null){
throw new IllegalArgumentException("head is empty");
} else {
nodeValue = head.getValue();
head = head.getNext();
}
return nodeValue;
}
}
Your DSAStack class is meant to be the interface between the user and linkedlist. So therefore the class provides the LIFO interface and forces it on the user. From here, it should hide the implementation from the linkedlist so the user doesn't have to worry about insertingLast or insertingFirst, they just want to insert.
So to answer your question. The DSAStack needs to perform the following actions:
- size() -> returns int size
- push(Object e) -> returns bool (able to be inserted)
- pop() -> returns Object and removes it from linkedlist
- peek() -> returns Object
- isEmpty() -> returns bool if empty
Your DSAStack isn't meant to hold any data. So you don't need the count or stack variable. Instead, we need to store these inside the DSALinkedList class. DSAStack should therefore instantiate a DSALinkedList object, pass the maxCapacity, and initiate the object.
When the user says that they want to use pop() on DSAStack, the class then needs to tell DSALinkedList, hey! I want to pop one of your objects! Now DSALinkedList needs to implement the details here.
Rewriting your code would be like this:
public DSAStack(int maxCapacity) {
list = new DSALinkedList[maxCapacity];
}
public int getCount() {
return list.size();
}
public boolean isEmpty() {
return list.isEmpty();
}
public boolean isFull() {
return list.isFull();
}
public void push(Object value) {
list.insertLast(value);
}
public Object pop() {
return list.removeLast();
}
public Object top() {
return list.peekLast();
}
public Iterator iterator() {
return list.iterator();
}
}