Sending a queue through a constructor in java? - java

The goal is to pass a data structure(queue) through a constructor and return a new queue once it goes through a method. I created a method of type Queue that converts from infix to postfix order. The problem is, when I pass the queue through the constructor, I am outputting all 'a's instead of the equation itself. So, I know that the linked list is passing the LENGTH of the queue, but not the characters themselves.
Output:
a+b+c/(d+f)
aaaaaaaaaaa
Main Class:
import java.io.*;
import java.lang.*;
class Convert
{
static int Prec(char ch)
{
switch (ch)
{
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
case '^':
return 3;
}
return -1;
}
public static QueueADT infixToPostFix(QueueADT in)
{
QueueADT infix = in;
QueueADT result = new QueueADT();
StackADT stack = new StackADT();
while(infix.empty() == false)
{
char c = infix.dequeue();
if (Character.isLetterOrDigit(c))
result.enqueue(c);
else if (c == '(')
stack.push(c);
else if (c == ')')
{
while (!stack.empty() && stack.peek() != '(')
result.enqueue(stack.pop());
stack.pop();
}
else // an operator is encountered
{
while (!stack.empty() && Prec(c) <= Prec(stack.peek()))
result.enqueue(stack.pop());
stack.push(c);
}
}
// pop all the operators from the stack
while (!stack.empty())
result.enqueue(stack.pop());
return result;
}
public static void main(String[] args)
{
QueueADT infix = new QueueADT();
String str = "a+b+c/(d+f)";
for(int i=0; i < str.length(); i++)
{
infix.enqueue(str.charAt(i));
System.out.print(str.charAt(i));
}
QueueADT postfix = infixToPostFix(infix);
System.out.println();
while(!postfix.empty())
{
System.out.print(postfix.dequeue());
}
}
}
Queue Class:
public class QueueADT
{
private int size;
private Node front;
private Node rear;
public QueueADT()
{
size = 0;
front = null;
rear = null;
}
public boolean empty()
{
return(size == 0);
}
public int size()
{
return size;
}
public void enqueue(char character)
{
Node newNode = new Node();
newNode.setData(character);
newNode.setNext(null);
if(this.empty())
{
front = newNode;
}
else
rear.setNext(newNode);
rear = newNode;
size++;
}
public char dequeue()
{
char i;
i = front.getData();
size--;
if(this.empty())
rear = null;
return i;
}
public char front()
{
return front.getData();
}
}
Stack class:
public class StackADT
{
private Node top;
private int size;
public StackADT()
{
top = null;
size = 0;
}
public boolean empty()
{
return (top == null);
}
public char peek()
{
return top.getData();
}
public int size()
{
return size;
}
public void push(char character)
{
Node newNode = new Node();
newNode.setData(character);
newNode.setNext(top);
top = newNode;
size++;
}
public char pop()
{
char i;
i = top.getData();
top = top.getNext();
size--;
return i;
}
public int onTop()
{
char i = pop();
push(i);
return i;
}
}
Node class:
public class Node
{
private char data;
private Node next;
public Node()
{
data = 0;
next = null;
}
public Node(char d)
{
data = d;
}
public Node(char d, Node n)
{
data = d;
next = n;
}
public void setData(char newData)
{
data = newData;
}
public void setNext(Node newNext)
{
next = newNext;
}
public char getData()
{
return data;
}
public Node getNext()
{
return next;
}
public void displayNode()
{
System.out.print(data);
}
}

Your implementation of dequeue method in QueueADT class is incorrect. You never change field "front", that's why when you call that method in your case, 'a' is always being returned. Add
front = front.getNext();
after line
char i = front.getData();
There are more problems with that code - try testing each of your methods separately, not only the program as a whole.

Related

How to extend child classes with a parent interface class

interface Iterator {
boolean hasnext();
int next();
}
class practice5 {
public static void main(String a[]) {
Stack s = new Stack();
Queue q = new Queue();
Linkedlist l = new Linkedlist();
s.push(100);
s.push(200);
q.Enque(300);
q.Enque(400);
l.add(500);
l.add(600);
Iterator itr;
itr = s;
while (!itr.hasnext()) {
System.out.println(itr.next());
}
itr = q;
while (!itr.hasnext()) {
System.out.println(itr.next());
}
itr = l;
while (itr.hasnext()) {
System.out.println(itr.next());
}
}
}
class Stack extends Iterator {
private int stack[];
private int top;
public Stack() {
stack = new int[10];
top = -1;
}
public void push(int val) {
top++;
stack[top] = val;
}
public boolean hasnext() {
if (top >= 0) {
return false;
} else {
return true;
}
}
public int next() {
return (stack[top--]);
}
}
class Queue extends Iterator {
private int queue[];
private int front, rear;
public Queue() {
queue = new int[10];
front = 0;
rear = 0;
}
public void Enque(int val) {
queue[rear] = val;
rear++;
}
public boolean hasnext() {
if (front < rear) {
return false;
} else {
return true;
}
}
public int next() {
return (queue[front++]);
}
}
class Linkedlist extends Iterator {
private int data;
private Linkedlist nw, next, prev, first, guest;
public Linkedlist() {
nw = next = prev = first = null;
}
public void add(int val) {
nw = new Linkedlist();
nw.data = val;
if (first == null) {
prev = first = nw;
} else {
prev.next = nw;
prev = nw;
}
}
public boolean hasnext() {
if (guest != 0) {
return true;
} else {
return false;
}
}
public int next() {
int curval;
curval = first.data;
first = first.next;
return (curval);
}
}
I'm expecting that I get an output for the above code.
I need to know if I'm extending the Stack, Queue and LinkedList classes wrongly with the interface class. Whenever I'm pass the iterator class object the instance of my child class objects, I am getting an error.
Also, in the LinkedList section when I call guest != 0, I'm getting an error Bad Operand. How can I check and print whether my guest is equal to zero or not?

Java linked list how to make a private method to handle searching

I trying and need help on how to create a private method to search a singly linked list.
My private search method is all the way at the bottom, how can I create a private method so i can then use it in an add/delete method?
I have been trying to do this for hours and I can't seem to get it right, i want to make a private search method to avoid loops later on in my other methods such as find add delete
public class LinkedBag<T> {
private Node first;
private int n;
public LinkedBag() {
}
public boolean isEmpty() {
return first == null;
}
public int size() {
return n;
}
public void add(T item) {
Node oldfirst = first;
first = new Node();
first.item = item;
first.next = oldfirst;
n++;
}
public int search(T item) {
if(item == null) {
throw new IllegalArgumentException("Cannot search null");
}
Node x = first;
int c = size() - 1;
while(x != null) {
if(x.item.equals(item)) {
return c;
}
x = x.next;
c--;
}
return -1;
}
private class Node {
private T item;
private Node next;
}
public static void main(String[] args) {
LinkedBag<Integer> intBag = new LinkedBag<>();
intBag.add(1);
intBag.add(2);
intBag.add(3);
System.out.println(intBag.search(1) == 0);
System.out.println(intBag.search(2) == 1);
System.out.println(intBag.search(3) == 2);
System.out.println(intBag.search(4) == -1);
}
}
You can create a search method in a single linked list which returns the position of the item or e.g. -1 in case the item was not found.
This search method will need to loop from the first node through its tailing nodes sequentially, extracts the item associated to each node and uses the equals method to try to find a match with the search item.
Here is a possible implementation in Java:
public int search(T item) {
Node x = first;
int c = size() - 1;
while(x != null) {
if(x.item.equals(item)) {
return c;
}
x = x.next;
c--;
}
return -1;
}
Below is a full example of how you can do it in a simple linked list with minimal generics support. Included is also a main method with a minimal unit test to prove the concept:
public class LinkedBag<T> {
private Node first;
private int n;
public LinkedBag() {
}
public boolean isEmpty() {
return first == null;
}
public int size() {
return n;
}
public void add(T item) {
Node oldfirst = first;
first = new Node();
first.item = item;
first.next = oldfirst;
n++;
}
public int search(T item) {
if(item == null) {
throw new IllegalArgumentException("Cannot search null");
}
Node x = first;
int c = size() - 1;
while(x != null) {
if(x.item.equals(item)) {
return c;
}
x = x.next;
c--;
}
return -1;
}
private class Node {
private T item;
private Node next;
}
public static void main(String[] args) {
LinkedBag<Integer> intBag = new LinkedBag<>();
intBag.add(1);
intBag.add(2);
intBag.add(3);
System.out.println(intBag.search(1) == 0);
System.out.println(intBag.search(2) == 1);
System.out.println(intBag.search(3) == 2);
System.out.println(intBag.search(4) == -1);
}
}

pop method in implemented LinkedQueue is removing all values and not the first one

With this implementation of a LinkedQueue, all the methods except the pop() method work fine. When using the pop() method all of the values in the stack disappear making it empty when it is supposed to remove the first value only
Here is the LinkedQueue class
import java.util.NoSuchElementException;
public class LinkedQueue
{
Node front, rear;
int size;
public LinkedQueue()
{
front = null;
rear = null;
size = 0;
}
public boolean isEmpty()
{
if(front == null)
return true;
else
return false;
}
public int getSize()
{
return size;
}
public void push(int data)
{
Node n = new Node(data);
if(isEmpty())
front = rear = n;
else
{
rear.setLink(n);
rear = n;
}
size++;
}
public int pop()
{
Node temp = new Node(front.getData());
if(isEmpty())
{
throw new IllegalAccessError();
}
else
{
front = temp.getLink();
size--;
}
return temp.getData();
}
public int peek()
{
if (isEmpty())
{
throw new NoSuchElementException("Stack is empty.");
}
else
{
return front.getData();
}
}
public String toString()
{
Node tempFront = front;
String returnStr = "Stack: [";
while(tempFront != null)
{
returnStr += tempFront.getData() + ", ";
tempFront = tempFront.getLink();
}
returnStr += "]";
return returnStr;
}
}
Here is the Driver used for the LinkedQueue class:
import java.util.Scanner;
public class Driver
{
public static void main(String[] args)
{
//declare variables and initialize scanner
Scanner key = new Scanner(System.in);
int size, choice, value, end;
end = 0;
//declare and initialize the stack
LinkedQueue queue1 = new LinkedQueue();
//loop to continue operations
while(end == 0)
{
//print out menu for commands
System.out.println("\t1) Push \n\t2) Pop \n\t3) Peek \n\t4) Size \n\t5) isEmpty \n\t6) End");
System.out.print("Please choose an option: ");
choice = key.nextInt();
//switch the choice and execute commands
switch (choice)
{
case 1: System.out.println("Please enter a value: ");
value = key.nextInt();
queue1.push(value);
System.out.println(queue1.toString());
break;
case 2: queue1.pop();
System.out.println(queue1.toString());
break;
case 3: queue1.peek();
System.out.println(queue1.peek());
System.out.println(queue1.toString());
break;
case 4: System.out.println("Size: " + queue1.getSize());
System.out.println(queue1.toString());
break;
case 5: if(queue1.isEmpty())
{
System.out.println("Stack is empty.");
}
else
System.out.println("Stack is NOT empty.");
System.out.println(queue1.toString());
break;
case 6: end = 1;
System.out.println("Goodbye!");
break;
}
}
}
}
I have also made my own Node class
public class Node
{
int data;
Node link;
//contructor
public Node(int d)
{
data = d;
link = null;
}
public int getData()
{
return data;
}
public Node getLink()
{
return link;
}
public void setData(int d)
{
data = d;
}
public void setLink(Node n)
{
link = n;
}
}
As mentioned before the only issue I have is with the pop() method, but if you see any other errors that will also help, it would be much appreciated.
Replace
front = temp.getLink();
with
front = front.getLink();

How to implement a rebalance in binary search tree?

I have already put in the following methods for a binary search tree:
import java.util.Collections;
import java.util.NoSuchElementException;
import java.util.ArrayList;
public class MyTree {
private class Node
{
public String data;
public int data2;
public Node left;
public Node right;
public Node(String data, Node left, Node right)
{
this.data = data;
this.left = left;
this.right = right;
}
}
private static Node root = null;
private int getHeight(Node subroot)
{
if (subroot == null)
return -1;
int maxLeft = getHeight(subroot.left);
int maxRight = getHeight(subroot.right);
return Math.max(maxLeft, maxRight) + 1;
}
public String toString()
{
return toString(this.root);
}
private String toString(Node subroot)
{
if (subroot==null)
return "";
return toString(subroot.left)+subroot.data+toString(subroot.right);
}
public boolean containsRecursive(String value)
{
return contains(value, this.root);
}
private boolean contains(String value, Node subroot)
{
if (subroot==null)
return false;
else if (value.equals(subroot.data))
return true;
else if (value.compareTo(subroot.data) < 0)
return contains(value, subroot.left);
else
return contains(value, subroot.right);
}
public boolean contains(String value) // not recursive
{
Node subroot = this.root;
while (subroot != null)
{
if (value.equals(subroot.data))
return true;
else if (value.compareTo(subroot.data) < 0)
subroot = subroot.left;
else
subroot = subroot.right;
}
return false;
}
public int addUp()
{
return addUp(this.root);
}
private int addUp(Node subroot)
{
if (subroot==null)
return 0;
return addUp(subroot.left)+subroot.data2+addUp(subroot.right);
} //data = String, data2 = int
public int count()
{
return count(this.root);
}
private int count(Node subroot)
{
if (subroot==null)
return 0;
return count(subroot.left)+1+count(subroot.right);
}
public int numberLess(int x)
{
return numberLess(this.root, x);
}
private int numberLess(Node subroot, int x)
{
if (subroot==null)
return 0;
if (x < subroot.data2)
return numberLess(subroot.left, x)+1+numberLess(subroot.right, x);
return numberLess(subroot.left, x)+numberLess(subroot.right, x);
}
public int findMax()
{
return findMax(this.root);
}
private int findMax(Node subroot) throws NoSuchElementException
{
if (subroot==null)
throw new NoSuchElementException();
return Math.max(findMax(subroot.left), findMax(subroot.right));
}
private ArrayList<Integer> addToList(Node subroot, ArrayList<Integer> a)
{
if (subroot!=null){
a.add(subroot.data2);
addToList(subroot.left, a).addAll(addToList(subroot.right, a));
return a;
}
return new ArrayList<Integer>();
}
private ArrayList<Integer> getSortedList(){
ArrayList<Integer> rawList = addToList(this.root, new ArrayList<Integer>());
Collections.sort(rawList);
return rawList;
}
public void rebalance(){
ArrayList<Integer> list = getSortedList();
}
}
How can I finish the rebalance method using the structure I already have? I'd like to use the sorted arraylist by finding the midpoints and recursively ordering them. I'm not sure how this would be approached using the way I have my tree set up (with the internal node class) so I'd like some help with this code.
Split the array in two equal sized portions. Take the median element as new root node.
Then split again the two portions and take the median element as second level nodes, etc.
Best implemented recursively....

Priority Queue using Priority List Misses All the Middle Values in Java

I am having an issue building a PList based Priority queue. Essentially, if I add items, all it ever does when I run a main function is spit out the highest and the lowest priority values.
Here is my PQueue insert item method
public class PQueue {
PList pq;
PList top;
public PQueue(){
this.pq=null;
}
public PQueue(int priority, char x){
this.pq=new PList(x, priority, null);
top=this.pq;
}
public boolean isEmpty(){
if(this.pq==null){
return true;
}else{
return false;
}
}
public void insertItem(int priority, char x){
if(isEmpty()){
this.pq=new PList(x, priority);
top=this.pq;
}else{
PList p=top;
while(p.priority<top.priority && p!=null){
p=p.next;
}PList n=new PList(x, priority, p.next);
p.next=n;
if(n.priority>top.priority){
top=n;
}
}
}
public void show(PrintStream p){
PList prnt= top;
while(prnt!=null){
p.println(prnt.content);
prnt=prnt.next;
}
}
}
Here is my linked list::
package se2s03;
public class PList {
public char content;
public int priority;
public PList next;
PList(final char a, final int b, final PList ll){
this.content=a;
this.priority=b;
this.next=ll;
}
PList(final char a, final int b){
this.content=a;
this.priority=b;
}
}
Here's a priority queue implementation using a linked list.
public class PQueue
{
private Node head;
public boolean isEmpty()
{
return head == null;
}
public void insert(int priority, Object obj)
{
if (head == null)
head = new Node(obj, priority);
else {
Node curr = head, prev = null;
while (curr != null && curr.priority > priority) {
prev = curr;
curr = curr.next;
}
if (prev == null)
head = new Node(obj, priority, head);
else
prev.next = new Node(obj, priority, curr);
}
}
public Object remove()
{
if (head == null)
return null;
Object val = head.val;
head = head.next;
return val;
}
public Object peek()
{
if (head == null)
return null;
return head.val;
}
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append("[");
Node prnt = head;
while (prnt != null) {
sb.append(prnt.val.toString() + ", ");
prnt = prnt.next;
}
return sb.substring(0, sb.length() - 2) + "]";
}
private class Node
{
Object val;
int priority;
Node next;
Node(Object val, int priority)
{
this(val, priority, null);
}
Node(Object val, int priority, Node next)
{
this.val = val;
this.priority = priority;
this.next = next;
}
}
public static void main(String[] args)
{
PQueue pq = new PQueue();
for (char ch = 'a'; ch <= 'z'; ch++)
pq.insert(ch - 'a', ch);
System.out.println(pq);
while (!pq.isEmpty())
System.out.print(pq.remove() + ", ");
}
}

Categories

Resources