Trouble searching a Stack in Java - java

I'm having trouble with programming a function in Java.
First i have implemented a Stack through a Single Linked List, like this:
public class ListStack<E> implements Stack<E> {
private static class Node<T> {
private T item;
private Node<T> next;
private Node(T item, Node<T> next) {
this.item = item;
this.next = next;
}
}
private Node<E> first;
private int size;
public ListStack() {
this.size = 0;
this.first = null;
}
#Override
public E peek() {
return first.item;
}
#Override
public void pop() {
first = first.next;
size--;
}
#Override
public void push(E e) {
Node<E> node = new Node<E>(e, first);
first = node;
size++;
}
#Override
public boolean isEmpty() {
return (first == null);
}
#Override
public int size() {
return size;
}
#Override
public Stack<E> reverse(){
ListStack<E> reversed = new ListStack<E>();
Node<E> node = first;
while(node != null){
reversed.push(node.item);
node = node.next;
}
return reversed;
}
}
Then i have created a stackof a type X. Here's that type's definition and constructor:
private String first, second;
private ListStack<String> text;
public X(String first, String second){
this.first = first;
this.second = second;
this.text = new ListStack<String>();
}
There are getters for both the strings firstand second, getFirst(), and getSecond(), respectively.
Then i want to write a function that basically, for each X of the stack, checks if the String second is equal to the String txt, passed as the function's argument. If it is, it returns X and deletes the Node from the stack, otherwise just returns null.
Here's my implementation of the method:
First, as a private attribute of the class:
private Stack<X> text; //for simplicity, let's assume the stack already contains values of type `X`.
Then:
private X getX(String txt) {
Stack<X> stack = text.reverse();
Stack<X> stack_final = new ListStack<X>();
X c;
String txt2;
boolean found = false;
for (int i = 0; i < stack.size() && !found; i++) {
c = stack.peek(); //extracts the element
txt2 = c.getSecond(); //gets the name
if (txt2.equals(txt)) {
found = true;
stack.pop();
} else
stack_final.push(c);
stack.pop();
}
if (found) {
text = stack_final;
return c;
}
else
return null;
}
What am i doing wrong ?
My guess is that i'm not updating the final stack correctly, with only the values that don't check, but i'm not sure it is that...

The main problem is the for-loop. Just step through it in your head:
i=0 stack=[1,2,3,4,5,6] stack_size=6
i=1 stack=[2,3,4,5,6] stack_size=5
i=2 stack=[3,4,5,6] stack_size=4
i=3 stack=[4,5,6] stack_size=3
the code actually breaks off after reading only half of the stack. You should rather use isEmpty() than a counter.
private X getX(String txt){
Stack<X> stack = text.reverse();
Stack<X> stack_final = new ListStack<X>();
X c = null;
while(!stack.isEmpty()){//transfer all items from stack to stack_final
//retrive and remove the first item from stack
X x = stack.peek();
stack.pop();
if(x.getSecond().equals(txt))//save x as searched item, if it matches
c = x;
//add the item to stack_final
stack_final.push(x);
}
//save stack_final as text (stack_final is a copy of text)
text = stack_final;
//c is either the searched item, or null, if no item was found
return c;
}
And btw., it's common that pop() returns the removed element.
public X pop(){
X res = first.item;
first = first.next;
return res;
}

You will get a NullPointerException if you try to peek() or pop() an empty stack!
public E peek() {
return first.item; // first is null if stack is empty!
}
public void pop() {
first = first.next; // first is null if stack is empty!
size--;
}
The Java Stack class throws an EmptyStackException in those cases.
Then I want to write a function that basically, for each X of the stack, checks if the String second is equal to the String txt, passed as the function's argument. If it is, it returns X and deletes the Node from the stack, otherwise just returns null.
Now, to achieve what you asked, you can simply do:
Stack<X> stack = text.reversed();
X elementFound = null;
while (!stack.isEmpty()) {
if (txt.equals(stack.peek().getSecond()) {
elementFound = stack.peek();
} else {
stackCopy.push(stack.peek());
}
stack.pop();
}
// now stack is empty and stackCopy contains stack reversed and without
// elementFound, if elementFound is not null (meaning it was found)
text = stackCopy; // stack was text reversed
return elementFound;

Related

Why does my iterator foreach loop never enter/execute?

I have a for-each loop in a method toString() that should iterate through elements in a generic FIFO queue (implemented using doubly linked list data structure) and concatenate the items in the queue onto the string a, which is returned to enqueue() which prints the string, which is a representation of my queue and its contents after an enqueue call. MY question is, why is the for-each not being executed/entered at all?
I tried inserting System.out.print("Hi"); inside the for-each, and it did not print. So I assume some block(s) of code is hindering it from executing properly.
// FIFOQueue is implemented using the structure double linked list (DLL)
// Generic, iterable
import java.util.Iterator;
import java.util.*;
public class FIFOQueueDLL<Item> implements Iterable<Item>{
private Node first;
private Node last;
private int length = 0;
// is the queue empty?
public boolean isEmpty(){
return length == 0;
}
private class Node{
Item item;
Node next;
Node previous;
}
// add an item
public void enqueue(Item n){
Node newnode = new Node();
newnode.item = n;
if(isEmpty()){
last = newnode;
} else {
first.previous = newnode;
}
newnode.next = first;
first = newnode;
length++;
System.out.println(this);
}
// remove and return the least recently added item
public Item dequeue(){
if(isEmpty()){
throw new NoSuchElementException();
}
Node t = last;
if(first == last){
first = null;
} else {
last.previous.next = null;
}
last = last.previous;
t.previous = null;
length--;
System.out.println(this.toString(););
return t.item;
}
public String toString(){
String a = "123";
for(Item item : this){
a = a + item;
}
return a;
}
public Iterator<Item> iterator(){
return new FIFOIterator();
}
private class FIFOIterator implements Iterator<Item>{
// Declare attribute
Node curr;
// Set attribute of node curr
public FIFOIterator(){
Node curr = first;
curr.item = first.item;
curr.next = first.next;
}
//private int i = length;
public boolean hasNext(){
return curr != null;
}
public Item next(){
Item a = curr.item;
curr = curr.next;
return a;
}
}
public static void main(String[] args){
FIFOQueueDLL<Character> c = new FIFOQueueDLL<Character>();
char b = 'b';
c.enqueue(b);
c.enqueue(b);
}
}
Expected output: 123b
123bb
Actual output: 123
123
Your FIFOIterator constructor creates a new object curr but does not set it to the field of the same class. Thus your field curr is null and hasNext returns false.
Change
// Set attribute of node curr
public FIFOIterator(){
Node curr = first;
curr.item = first.item;
curr.next = first.next;
}
to
// Set attribute of node curr
public FIFOIterator(){
this.curr = first;
}
I debugged this codeblock:
public String toString(){
String a = "123";
for(Item item : this){
a = a + item;
}
return a;
}
and saw that "this" holds the value of the String a. Do you want to change Item class to Character class instead, and call toCharArray() method on a instead of using this. This is what I am talking about:
public String toString(){
String a = "123";
for(Character item : a.toCharArray()){
a = a + item;
}
return a;
}
you will get into the loop and be able to append any new character you want. Hope this helps.

How to write recursion get methods in doubly linkedlist?

here is my code
public class LinkedListDeque<T> implements Deque {
private Node sentinel;
private int size;
private static class Node<T> {
private T item;
private Node pre;
private Node next;
public Node(T i, Node p, Node n) {
item = i;
pre = p;
next = n;
}
public LinkedListDeque() {
size = 0;
sentinel = new Node(null, null, null);
sentinel.next = sentinel;
sentinel.pre = sentinel;
}
public LinkedListDeque(T item) {
size = 1;
Node first = new Node(item, sentinel, sentinel);
sentinel = new Node(null, first, first);
}
public Object getRecursive(int index) {}
}
I just can't figure out how to do it. I can do it in a interation way. I don't know where to start to build a recursion methods.
public Node getNode(Node n, int index, int pos) {
if (index == pos) {
return n;
}
if (index > pos || n == null) {
return null;
}
return getNode(n.next, index, pos++);
}
I believe this is what you want, and the initial call is with pos=0 and the head of the LinkedList.
I think you need to look up how recursion works though, because you failed to even attempt the problem.

Evaluate a Postfix Expression Using a Singly Linked List

I'm writing a program that asks the user for a postfix expression, and then outputs the result to the expression. I am attempting to do this using a Singly Linked List, and using the Adapter Pattern to create a stack.
The code for the SinglyLinkedList class, the LinkedStack class, and the Stack implementation are all straight out of a Data Structures book that I own. So the SinglyLinkedListTest class is the only one that has my own code in it (and has errors).
I've written a program that simply uses a stack to evaluate a postfix expression before, but I'm getting confused this time with the extra classes included.
I'm sure I have a ton of errors, but the most obvious ones to me are in my SinglyLinkedListTest class, every time I push a value onto the stack. I know the issue is that I am attempting to push Objects and characters onto the stack instead of the arguments that match push(E e), but I don't know how to alter my code to make this work.
Any suggestions or input would be greatly appreciated.
Here is my Stack Implementation:
package PostFix;
public interface Stack<E>
{
int size();
boolean isEmpty();
void push(E e);
E pop();
}
Here is my LinkedStack class:
package PostFix;
public class LinkedStack <E> implements Stack<E>
{
private SinglyLinkedList<E> list = new SinglyLinkedList<>();
public LinkedStack()
{
}
public int size()
{
return list.size();
}
public boolean isEmpty()
{
return list.isEmpty();
}
public void push(E e)
{
list.addFirst(e);
}
public E pop()
{
return list.removeFirst();
}
}
Here is my SinglyLinkedList class:
package PostFix;
public class SinglyLinkedList<E>
{
private static class Node<E>
{
private E element;
private Node<E> next;
public Node(E e, Node<E> n)
{
element = e;
next = n;
}
public E getElement()
{
return element;
}
public Node<E> getNext()
{
return next;
}
}
private Node<E> head = null;
private Node<E> tail = null;
private int size = 0;
public SinglyLinkedList()
{
}
public int size()
{
return size;
}
public boolean isEmpty()
{
return size == 0;
}
public void addFirst(E e)
{
head = new Node<>(e, head);
if (size == 0)
{
tail = head;
}
size++;
}
public E removeFirst()
{
if (isEmpty())
{
return null;
}
E answer = head.getElement();
head = head.getNext();
size--;
if (size == 0)
{
tail = null;
}
return answer;
}
}
Here is my final SinglyLinkedListTest class:
package PostFix;
import java.util.Scanner;
public class SinglyLinkedListTest
{
public static void main(String[] args)
{
Double num1, num2, answer;
char c;
Stack<Double> stack = new LinkedStack<>();
Scanner input = new Scanner(System.in);
System.out.println("Enter the expression you would like to evaluate: ");
String someString = input.nextLine();
for (int index = 0; index < someString.length(); index++)
{
c = someString.charAt(index);
if (Character.isDigit(c))
{
stack.push((double)Character.digit(c, 10));
}
else if (c == '+')
{
num2 = stack.pop();
num1 = stack.pop();
answer = num1+num2;
stack.push(answer);
}
else if (c == '-')
{
num2 = stack.pop();
num1 = stack.pop();
answer = num1-num2;
stack.push(answer);
}
else if (c == '*')
{
num2 = stack.pop();
num1 = stack.pop();
answer = num1*num2;
stack.push(answer);
}
else if (c == '/')
{
num2 = stack.pop();
num1 = stack.pop();
answer = num1/num2;
stack.push(answer);
}
}
System.out.println("The result is: " + stack.pop());
}
}
Stack<String> buffer = new LinkedStack<>();
Poor name: call it stack.
You've declared it as Stack<String> but you're pushing chars:
buffer.push(someString.charAt(index));
and Objects:
buffer.push(answer);
and popping ints:
num1 = buffer.pop();
You are never either pushing or popping strings.
Just make up your mind. You should be pushing and popping ints, or longs, or doubles, or BigDecimals, depending on what precision you need.
EDIT
buffer.push((double)c);
is invalid. You're pushing the ASCII value, not the numeric value it corresponds to. You need
buffer.push((double)Character.digit(c, 10));
You also need an else after each if block: if the character is a digit, it won't be a +, and if it's a + it won't be a -, etc.

issues when managing multiple stacks

Investigating a solution to manage multiple stacks, posted the problem and code I am debugging. The question is, why function popAt(int index) shift from bottom of next sub-stack? Does it because of the next element (in the order of stack push) of top of sub-stack 1, is bottom element of sub-stack 2? I am not sure if this behavior is correct, and whether the expected behavior is, after pop element of stack 1, the next element to pop is the element in stack 1 which is under previous top, other than bottom of next stack?
Imagine a (literal) stack of plates. If the stack gets too high, it might topple. Therefore, in real life, we would likely start a new stack when the previous stack exceeds some threshold. A data structure SetOfStacks that mimics this. SetOfStacks should be composed of several stacks, and should create a new stack once the previous one exceeds capacity. SetOfStacks.push() and SetOfStacks.pop() should behave identically to a single stack (that is, pop() should return the same values as it would if there were just a single stack), and function popAt(int index) which performs a pop operation on a specific sub-stack.
public class SetOfStacks {
ArrayList<Stack> stacks = new ArrayList<>();
public int capacity;
public SetOfStacks(int capacity) {
this.capacity = capacity;
}
public Stack getLastStack() {
if (stacks.size() == 0) return null;
return stacks.get(stacks.size() - 1);
}
public void push(int v) { /* see earlier code */
}
public int pop() {
Stack last = getLastStack();
System.out.println(stacks.size());
int v = last.pop();
if (last.size == 0) stacks.remove(stacks.size() - 1);
return v;
}
public int popAt(int index) {
return leftShift(index, true);
}
public int leftShift(int index, boolean removeTop) {
Stack stack = stacks.get(index);
int removed_item;
if (removeTop) removed_item = stack.pop();
else removed_item = stack.removeBottom();
if (stack.isEmpty()) {
stacks.remove(index);
} else if (stacks.size() > index + 1) {
int v = leftShift(index + 1, false);
stack.push(v);
}
return removed_item;
}
}
public class Stack {
private int capacity;
public Node top, bottom;
public int size = 0;
public Stack(int capacity) {
this.capacity = capacity;
}
public boolean isAtCapacity() {
return capacity == size;
}
public void join(Node above, Node below) {
if (below != null) below.above = above;
if (above != null) above.below = below;
}
public boolean push(int v) {
if (size >= capacity) return false;
size++;
Node n = new Node(v);
if (size == 1) bottom = n;
join(n, top);
top = n;
return true;
}
public int pop() {
Node t = top;
top = top.below;
size--;
return t.value;
}
public boolean isEmpty() {
return size == 0;
}
public int removeBottom() {
Node b = bottom;
bottom = bottom.above;
if (bottom != null) bottom.below = null;
size--;
return b.value;
}
}
thanks in advance,
Lin
leftShift() in your code may be called recursively with increasing index, that's why if you call it with index of 1 it may pop from stack #2 then (and, in a case when all stacks were 1 element in size, it will continue with stack #3, #4 and so on :( )
Here is my simple solution of stacks of plate using linkedList in java.
class Stack<T>{
Node top;
NodeTop nodeTop;
int count = 1;
int i = 3;
static class Node<T>{
private T data;
private Node next;
Node(T data){
this.data = data;
next = null;
}
}
static class NodeTop<T>{
private Node<T> top;
private NodeTop<T> next;
NodeTop(Node top){
this.top = top;
}
}
public void push(T data){
if(count > i){
System.out.println("Starting new row of plates");
NodeTop temp = new NodeTop(top);
temp.next = nodeTop;
nodeTop = temp;
top = null;
i = i + 3;
}
Node temp = new Node(data);
temp.next = top;
top = temp;
count++;
System.out.println(data);
}
public void pop(){
if(top == null){
System.out.println("Current row does not contains any plates, moving to next row");
if(nodeTop == null){
System.out.println("No Plates left");
return;
}
top = nodeTop.top;
nodeTop = nodeTop.next;
i = i - 3;
}
System.out.println(top.data);
top = top.next;
count--;
}
}

Reassign `this` in Java class

I'm just fooling around in Java right now, trying to implement something similar to a stack using linked lists.
class ListStack {
int value;
int size;
ListStack next;
public ListStack (int add) {
this.size = 1;
this.value = add;
this.next = null;
}
public void push (int add) {
this.next = this;
this.value = add;
this.size++;
}
public int pop() {
if (this.size == 0) { throw new EmptyListStackException(); }
int i = this.value;
this = this.next;
this.size--;
return i;
}
public int size() {
return this.size;
}
public int peek() {
return this.value;
}
}
Basically it's an insertion-in-front linked list which also removes from front. NetBeans pops an error when I try to do this = this.next; it says I cannot reassign final value this.
I'd like my final implementation to do something like the below:
ListStack var = new ListStack(5); //var is now 5 -> null
var.push(3); //var is now 3 -> 5 -> null
int val = varr.pop(); //var is now 5 -> null, val == 3
Commenting put that this = this.next code, the rest seems to work.
ListStack a = new ListStack(5);
System.out.println(a.size()); //prints 1
System.out.println(a.peek()); //prints 5
a.push(4);
System.out.println(a.size()); //prints 2
System.out.println(a.peek()); //prints 4
a.push(6);
System.out.println(a.size()); //prints 3
System.out.println(a.peek()); //prints 6
a.push(1);
System.out.println(a.size()); //prints 4
System.out.println(a.peek()); //prints 1
//a is 1 -> 6 -> 4 -> 5 -> null
There is a conceptual error in your code: basically you are not creating any new stack element with your push method.
But the problem is that calling the class listStack becomes misleading, because actually what you want to create are new elements of the stack, so you should create a class node maybe.
Moreover you can't ovveride "this" because it is a java keyword and it always refers to the current object.
To give you a hint of what to do to implement a stack as a linked list you should create class Node with a value field value and a reference to the previous Node (the first node will just have a null pointer) .
In the class ListStackyou should have a reference to the last node and its push() method should create a new Node and set this one as the new last node.
Let me point you in right direction. As others have commented, this stack does not work properly Consider doing something like this:
public class ListStack {
private class Node {
private int value;
private Node next;
//inner class which holds your each element and reference to next
//fill all details required
}
private Node head;
private int size;
public ListStack() {
head = null;
size = 0;
}
public void push(int value) {
Node temp = new Node(value);
if(head == null)
head = temp;
else {
temp.setNext(head); // provide link to already existing stack
head = temp; // bring new element on top
}
}
public int pop() {
if(head==null);
//throw exception
int temp = head.getValue();
head = head.getNext(); //remove element and bring down the stack
return temp;
}
}

Categories