How to extend child classes with a parent interface class - java

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?

Related

Sending a queue through a constructor in 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.

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);
}
}

Issue with creating Immutable Queue

I am using the following code to make an immutable queue.
import java.util.NoSuchElementException;
import java.util.Queue;
public class ImmutableQueue<E> {
//Two stacks are used. One is to add items to the queue(enqueue) and
//other is to remove them(dequeue)
private ImmutableQueue(ReversableStack<E> order, ReversableStack<E> reverse) {
this.order = order;
this.reverse = reverse;
}
//initially both stacks are empty
public ImmutableQueue() {
this.order = ReversableStack.emptyStack();
this.reverse = ReversableStack.emptyStack();
}
public ImmutableQueue<E> enqueue(E e) {
if (null == e)
throw new IllegalArgumentException();
return new ImmutableQueue<E>(this.order.push(e), this.reverse);
}
public ImmutableQueue<E> dequeue() {
if (this.isEmpty())
throw new NoSuchElementException();
if (!this.reverse.isEmpty()) {
return new ImmutableQueue<E>(this.order, this.reverse.tail);
} else {
return new ImmutableQueue<E>(ReversableStack.emptyStack(),
this.order.getReverseStack().tail);
}
}
private static class ReversableStack<E> {
private E head; //top of original stack
private ReversableStack<E> tail; //top of reversed stack
private int size;
//initializing stack parameters
private ReversableStack(E obj, ReversableStack<E> tail) {
this.head = obj;
this.tail = tail;
this.size = tail.size + 1;
}
//returns a new empty stack
public static ReversableStack emptyStack() {
return new ReversableStack();
}
private ReversableStack() {
this.head = null;
this.tail = null;
this.size = 0;
}
//Reverses the original stack
public ReversableStack<E> getReverseStack() {
ReversableStack<E> stack = new ReversableStack<E>();
ReversableStack<E> tail = this;
while (!tail.isEmpty()) {
stack = stack.push(tail.head);
tail = tail.tail;
}
return stack;
}
public boolean isEmpty() {
return this.size == 0;
}
public ReversableStack<E> push(E obj) {
return new ReversableStack<E>(obj, this);
}
}
private ReversableStack<E> order;
private ReversableStack<E> reverse;
private void normaliseQueue() {
this.reverse = this.order.getReverseStack();
this.order = ReversableStack.emptyStack();
}
public E peek() {
if (this.isEmpty())
throw new NoSuchElementException();
if (this.reverse.isEmpty())
normaliseQueue();
return this.reverse.head;
}
public boolean isEmpty() {
return size() == 0;
}
//returns the number of items currently in the queue
public int size() {
return this.order.size + this.reverse.size;
}
public static void main(String[] args)
{
ImmutableQueue<Integer> newQueue = new ImmutableQueue<Integer>();
newQueue.enqueue(5);
newQueue.enqueue(10);
newQueue.enqueue(15);
int x = newQueue.size();
//ImmutableQueue<Integer> x = newQueue.dequeue();
System.out.println(x);
}
}
But whenever I try to do a dequeue, I get a NoSuchElementException. Also, the newQueue.size function also returns 0.
What am I doing wrong ?
Thanks
You are missing the new ImmutableQueue reference..
since enqueue() method returns a new instance of ImmutableQueue
public ImmutableQueue<E> enqueue(E e) {
if (null == e)
throw new IllegalArgumentException();
return new ImmutableQueue<E>(this.order.push(e), this.reverse);
}
But on your main method you are discarding that object
public static void main(String[] args)
{
ImmutableQueue<Integer> newQueue = new ImmutableQueue<Integer>();
newQueue.enqueue(5);
newQueue.enqueue(10);
newQueue.enqueue(15);
int x = newQueue.size();
//ImmutableQueue<Integer> x = newQueue.dequeue();
System.out.println(x);
}
change your call to:
newQueue = newQueue.enqueue(5);
int x = newQueue.size();
System.out.println(x);
and you will see the size will change

LinkedList - delete(Object) method works strange - deleting last element doesn't work properly

I have LinkedList with test program. As you can see in that program I add some Students to the list. I can delete them. If I choose s1,s2,s3 oraz s4 to delete everything runs well, and my list is printed properly and information about number of elements is proper. But if I delete last element (in this situation - s5) info about number of elements is still correct, but this element is still printed. Why is that so? Where is my mistake?
public class Lista implements List {
private Element head = new Element(null); //wartownik
private int size;
public Lista(){
clear();
}
public void clear(){
head.setNext(null);
size=0;
}
public void add(Object value){
if (head.getNext()==null) head.setNext(new Element(value));
else {
Element last = head.getNext();
//wyszukiwanie ostatniego elementu
while(last.getNext() != null)
last=last.getNext();
// i ustawianie jego referencji next na nowowstawiany Element
last.setNext(new Element(value));}
++size;
}
public Object get(int index) throws IndexOutOfBoundsException{
if(index<0 || index>size) throw new IndexOutOfBoundsException();
Element particular = head.getNext();
for(int i=0; i <= index; i++)
particular = particular.getNext();
return particular.getValue();
}
public boolean delete(Object o){
if(head.getNext() == null) return false;
if(head.getNext().getValue().equals(o)){
head.setNext(head.getNext().getNext());
size--;
return true;
}
Element delete = head.getNext();
while(delete != null && delete.getNext() != null){
if(delete.getNext().getValue().equals(o)){
delete.setNext(delete.getNext().getNext());
size--;
return true;
}
delete = delete.getNext();
}
return false;
}
public int size(){
return size;
}
public boolean isEmpty(){
return size == 0;
}
public IteratorListowy iterator() {
return new IteratorListowy();
}
public void wyswietlListe() {
IteratorListowy iterator = iterator();
for (iterator.first(); !iterator.isDone(); iterator.next())
{
System.out.println(iterator.current());
}
System.out.println();
}
public void infoOStanie() {
if (isEmpty()) {
System.out.println("Lista pusta.");
}
else
{
System.out.println("Lista zawiera " + size() + " elementow.");
}
}
private static final class Element{
private Object value;
private Element next; //Referencja do kolejnego obiektu
public Element(Object value){
setValue(value);
}
public void setValue(Object value) {
this.value = value;
}
public Object getValue() {
return value;
}
//ustawia referencję this.next na obiekt next podany w atgumencie
public void setNext(Element next) {
if (next != null)
this.next = next;
}
public Element getNext(){
return next;
}
}
private class IteratorListowy implements Iterator{
private Element current;
public IteratorListowy() {
current = head;
}
public void next() {
current = current.next;
}
public boolean isDone() {
return current == null;
}
public Object current() {
return current.value;
}
public void first() {
current = head.getNext();
}
}
}
test
public class Program {
public static void main(String[] args) {
Lista lista = new Lista();
Iterator iterator = lista.iterator();
Student s1 = new Student("Kowalski", 3523);
Student s2 = new Student("Polański", 45612);
Student s3 = new Student("Karzeł", 8795);
Student s4 = new Student("Pałka", 3218);
Student s5 = new Student("Konowałek", 8432);
Student s6 = new Student("Kłopotek", 6743);
Student s7 = new Student("Ciołek", 14124);
lista.add(s1);
lista.add(s2);
lista.add(s3);
lista.add(s4);
lista.add(s5);
lista.wyswietlListe();
lista.delete(s5);
lista.wyswietlListe();
lista.infoOStanie();
lista.clear();
lista.infoOStanie();
}
}
The problem is that your setNext(Element next) method does not set anything if next == null. And that is the case for the last element of your list.
So when you call delete.setNext(delete.getNext().getNext());, nothing is actually set because delete.getNext().getNext() is null!
Remove the if (next != null) condition in setNext and it will work.

Creating Minimum number and Addition Function of LinkedList

I'm having a problem with trying the logic and trying to write a min and additionMerge function and their recursive versions of the function that takes at least one list as an argument (the first node of the list). This will be a private helper function that is called by a wrapper function that is a member function of the LinkedList class.
public class LinkedList {
private static class ListNode {
public int firstItem;
public ListNode restOfList;
}
private ListNode first;
/**
* Create an empty list.
*/
public LinkedList() {
first = null;
}
public LinkedList(int n) {
first = countDown(n);
}
public LinkedList(String s) {
String[] temp = s.split(",");
for (int i = temp.length-1; i >= 0; i--) {
first = insertAtFront(first, Integer.parseInt(temp[i]));
}
}
public int length() {
return length(first);
}
private static int length(ListNode list) {
if (list == null) {
return 0;
}
int temp = length(list.restOfList);
return temp + 1;
}
public boolean contains(int value) {
return contains(first, value);
}
private static boolean contains(ListNode list, int value) {
if (list == null) {
return false;
}
if (list.firstItem == value) {
return true;
}
return contains(list.restOfList, value);
}
public int sum() {
return sum(first);
}
private static int sum(ListNode list) {
if (list == null) {
return 0;
}
return sum(list.restOfList) + list.firstItem;
}
public int count(int target) {
return count(first, target);
}
private static int count(ListNode list, int target) {
if (list == null) {
return 0;
}
int temp = count(list.restOfList, target);
if (list.firstItem == target) {
temp++;
}
return temp;
}
public void replace(int oldValue, int newValue) {
replace(first, oldValue, newValue);
}
private static void replace(ListNode list, int oldValue, int newValue) {
if (list == null) {
return;
}
replace(list.restOfList, oldValue, newValue);
if (list.firstItem == oldValue) {
list.firstItem = newValue;
}
}
public void insertAtFront(int n) {
first = insertAtFront(first, n);
}
private static ListNode insertAtFront(ListNode list, int n) {
ListNode answer = new ListNode();
answer.firstItem = n;
answer.restOfList = list;
return answer;
}
private static ListNode countDown(int n) {
if (n == 1) {
ListNode answer = new ListNode();
answer.firstItem = 1;
answer.restOfList = null;
return answer;
}
ListNode temp = countDown(n - 1);
ListNode answer = insertAtFront(temp, n);
return answer;
}
public void insertAtBack(int item) {
first = insertAtBack(first, item);
}
private static ListNode insertAtBack(ListNode list, int item) {
if (list == null) {
ListNode answer = new ListNode();
answer.firstItem = item;
answer.restOfList = null;
return answer;
}
//List answer = new ListNode();
//answer.firstItem = list.firstItem;
ListNode temp = insertAtBack(list.restOfList, item);
//answer.restOfList = temp;
list.restOfList = temp;
return list;
}
public void concatenate(LinkedList otherList) {
this.first = concatenate(this.first, otherList.first);
}
private static ListNode concatenate(ListNode list1, ListNode list2) {
if (list1 == null) {
return list2;
}
ListNode temp = concatenate(list1.restOfList, list2);
list1.restOfList = temp;
return list1;
}
public void filter(int item) {
first = filter(first, item);
}
#Override
public String toString() {
if (first == null) {
return "";
}
StringBuilder sb = new StringBuilder(256);
sb.append(first.firstItem);
for (ListNode current = first.restOfList;
current != null;
current = current.restOfList) {
sb.append(',');
sb.append(current.firstItem);
}
return sb.toString();
}
private static ListNode filter(ListNode list, int item) {
if (list == null) {
return null;
}
ListNode temp = filter(list.restOfList, item);
if (list.firstItem == item) {
return temp;
}
list.restOfList = temp;
return list;
}
public int min() throws RuntimeException {
if (first == null)
throw new RuntimeException("List is Empty");
else
return min();
}
// * A private recursive helper function that returns the minimum item in a
* list whose first node is the argument list.
private static int min(ListNode list) throws RuntimeException {
if (list == null) {
return 0;
}
}
public void additionMerge(LinkedList l2) {
}
* Every node in the list that begins with node
* node1 is increased by the ammount of the corresponding
* node in the list that begins with node node2.
* If one list is longer than the other, the missing nodes
* in the shorter list are assumed to be 0.
private static ListNode additionMerge(ListNode node1, ListNode node2) {
if (list == null) {
return null;
}
}
}
If this is not homework, then my advice is:
Don't write your own LinkedList class. Use the existing out, and add the extra functionality either as a helper class or by extending the existing class.
If you do decide to implement your own linked list class, then you should beware of using recursion. Recursion gives a neat soltion, but there is a major drawback with recursion in Java. The JVM does not do tail call optimization, so a recusive algorithm that recurses deeply (e.g. recursively traversing a long list) is liable to cause a StackOverflowError.

Categories

Resources