So, I got this comparable class:
public class JakeInteger implements Comparable<JakeInteger>{
private int value;
public JakeInteger(int value){
this.value = value;
}
#Override
public int compareTo(JakeInteger other) {
if (other.getValue() < value)
return -1;
if (other.getValue() > value)
return 1;
return 0;
}
public String toString(){
return String.valueOf(value);
}
public int getValue(){return value;}
I think I've got it right...
Then I have my own linked list of generic objects: (no need to read all of it)
public class GenericList<Type extends Comparable> implements Iterable<Comparable>{
private Node first = null;
private int length = 0;
#Override
public Iterator<Comparable> iterator() {return new ListIterator();}
private class ListIterator implements Iterator<Comparable>{
private Node current = first;
#Override
public boolean hasNext() {return current != null;}
public Node getCurrentNode(){
return current;
}
#Override
public Comparable next() {
Comparable item = current.item;
current = current.next;
return item;
}
}
private class Node{
Comparable<Type> item;
Node next;
}
public boolean isEmpty(){
if (first == null)
return true;
return false;
}
public void prepend(Comparable item){
Node second = first;
first = new Node();
first.item = item;
first.next = second;
length++;
}
public void append(Comparable item){
if (length == 0){
prepend (item);
return;
}
Node last = first;
for (int i = 0; i<length-1; i++)
last = last.next;
last.next = new Node();
last.next.item = item;
length++;
}
public Comparable first(){
return first.item;
}
public Comparable pop(){//rest
Comparable oldFirst = first.item;
first = first.next;
return oldFirst;
}
public int getLength(){
return length;
}
// it
public Comparable getByIndex(int Index){
if (Index > this.length - 1)return null;
Iterator<Comparable> it = iterator();
for (int i = 0; i < Index-1; i++){
it.next();
}
return it.next();
}
public Node getNodeByIndex(int Index){
Node node = first;
for (int i = 0; i < Index; i++)
node = node.next;
return node;
}
public void bubbleSort(){
if (length <= 0)
return;
Node tempNode = first;
int R = length -2;
boolean swapped = true;
while (R >= 0 && swapped){
swapped = false;
for (int i = 0; i <= R; i++){
//if(tempNode.item.compareTo((Type) tempNode.next.item) )
}
}
}
private void swapWithNext(Node a){
Comparable itema = a.item;
a.item = a.next.item;
a.next.item = itema;
}
So far everything works fine, but now, when I'm trying to implement a bubble sort , the item.compareTo() doesn't exist. The way I see it the Item should always have implemented the comparable interface and have access to this method. What am I doing wrong?
Change the implements clause of yourGenericList` from:
public class GenericList<Type extends Comparable> implements Iterable<Comparable>{
To:
public class GenericList<Type extends Comparable<Type>> implements Iterable<Type>{
Just using Comparable is incomplete by itself; you need to say what it should be able to compare against. An in your case, that should be the type variable Type.
Throughout your class, you should also change Comparable to Type, and in the inner class ListIterator, you should also define a type variable (but to avoid confusion, don't call it Type but something else like Type2, because it will be independent from the type variable Type in GenericList)
public Iterator<Type> iterator() {return new ListIterator<Type>();}
private class ListIterator<Type2 extends Comparable<Type2>> implements Iterator<Type2>{
public Type2 next() {
// ...
}
// ...
public void prepend(Type2 item){
// ...
}
public void append(Type2 item){
// ...
}
public Type2 first(){
// ...
public Type2 pop(){
// ...
Related
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?
Hi,
Update: Thanks for all your suggestion
assuming that, this exercise it's like a rebus,
I have a list of numbers made with the concept of Cons and Nil,
List l = new Cons(**3**, new Cons(**2**,new Cons(**1**, new
Cons(**4**, new Cons(**1**, new Nil())))));
and I want to count how many of them are immediately followed by a lower number, recursively.
For example
[5,0,5,3].count() == 2, [5,5,0].count() == 1
The count() method is made by me (it cannot have any parameters), the rest is default, and I can't make and other method or use already defined one's like add(),size()...
The "NEXT" must have the next value after the current elem but I can't get a solution.
Any solutions are welcome.
abstract class List {
public abstract boolean empty();
public abstract int first();
public abstract int count();
}
class Cons extends List {
private int elem;
private List next;
public Cons(int elem, List next) {
this.elem = elem;
this.next = next;
}
public boolean empty(){
return false;
}
public int first(){
return elem;
}
#Override
public int count() {
if(elem>NEXT) {
return 1 + next.count();
}else {
return next.count();
}
}
```![enter image description here](https://i.stack.imgur.com/kWo0v.jpg)
The following code will create a recursive list with N elements with N value being defined by the size of the amount of elements found in the int array called elements in RecursiveList class. Call the startRecursion() method to create a recursive list with the defined elements and call count() to get the amount of elements in the array that are immediately followed by a lower number.
Main Class
This your application entry point:
public static void main(String[] args) {
int count = RecursiveList.startRecursion().count();
System.out.printf("List has %d recursive elements", count);
}
RecursiveList Class
abstract class RecursiveList {
protected static int index = -1;
protected static int[] elements = new int[]{ 5,2,1,4,3,2,6 };
public static RecursiveList startRecursion() {
return new Cons();
}
public abstract boolean empty();
public abstract int count();
public abstract Integer getElement();
public static int incIndex() {
return index += 1;
}
}
Cons Class
public class Cons extends RecursiveList {
private static int result;
private final Integer elem;
private final RecursiveList prev;
private final RecursiveList next;
private Cons(Cons parent) {
prev = parent;
elem = incIndex() < elements.length ? elements[index] : null;
System.out.printf("Creating new Cons with element %d(%d)%n", elem, index);
next = elem != null ? new Cons(this) : null;
}
Cons() {
this(null);
}
public boolean empty() {
return false;
}
#Override
public /*#Nullable*/ Integer getElement() {
return elem;
}
#Override
public int count() {
if (elem != null)
{
if (prev != null && elem < prev.getElement())
result += 1;
if (next != null) {
return next.count();
}
}
return result;
}
}
EDIT
Alright here is the answer you were actually looking for. This completely conforms to the limitations imposed on this exercise that you provided. The solution uses pure Java, neither the class nor any of it's method or field declarations were modified in any way and no such new elements were added. I've only added the implementation where the exercise said you should.
Main Class
public static void main(String[] args) {
List l = new Cons(3, new Cons(2,new Cons(1, new
Cons(4, new Cons(1, new Nil())))));
assert l.count() == 3;
l = new Cons(5, new Nil());
assert l.count() == 0;
l = new Cons(5, new Cons(5, new Cons(0, new Nil())));
assert l.count() == 1;
l = new Cons(5, new Cons(0, new Cons(5, new Cons(3, new Nil()))));
assert l.count() == 2;
System.out.println("All tests completed successfully!");
}
Cons Class
import java.util.NoSuchElementException;
public class Cons extends List {
private int elem;
private List next;
public Cons(int elem, List next) {
this.elem = elem;
this.next = next;
}
public boolean empty()
{ return false; }
public int first()
{ return elem; }
public int count()
{
try {
if (first() > next.first()) {
return 1 + next.count();
}
else return next.count();
}
catch (NoSuchElementException e) {
return 0;
}
}
}
Nil Class
import java.util.NoSuchElementException;
public class Nil extends List {
public boolean empty()
{ return true; }
public int first()
{ throw new NoSuchElementException(); }
public int count()
{
throw new IllegalAccessError();
}
}
public int NEXT(){
if(next!=null)
return next.first()
else
throw new Exception("No next element")
}
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);
}
}
Here is my class:
public class LinkedListSet implements Set {
private class Node //much easier as a private class; don't have to extend
{
private int data;
private Node next;
public Node (){}
public Node (int x)
{
data = x;
}
public int data()
{
return data;
}
public Node next()
{
return next;
}
}
private Node first;
private int Size;
private int whichList; //used to identify the particular LL object
Here is my interface:
public interface Set {
public boolean isEmpty();
public void makeEmpty();
public boolean isMember(int x);
public void add(int x);
public void remove(int y);
public void union(Set other, Set result);
public void intersection (Set other, Set result);
public void difference (Set other, Set result);
#Override
public String toString();
#Override
public boolean equals(Object other);
public void setList(int i); //i added this to use it as an identifier for each
//list element in the set array
public String getListId(); //these two extra methods make life easier
}
I have a method like this (in the LinkedListSet class):
public void difference (Set other, Set result)
{
if (other.isEmpty())
{
System.out.println("The set is empty before cast");
}
LinkedListSet othr = (LinkedListSet) other;
LinkedListSet res = (LinkedListSet) result;
if (this.isEmpty() || othr.isEmpty())
{
if (othr.isEmpty())
System.out.println("The set is empty after cast");
if (this.isEmpty())
System.out.println("This is also empty");
return;
}
differenceHelper(this.first, othr.first, res);
result = res;
}// the print statements were added for debugging
The problem is, in the above method I am unable to cast the Set Other into its linked list implementation. When I call this method in the main program, the parameter is actually of type linked list (so I don't get any errors obviously).
However, all the instance variables are null. The list is empty before and after I cast it (when it actually isn't empty). I know this is because the interface doesn't include any information about the Nodes, but is there anything I can do other than editing the interface to incorporate the Node?
I hope I've made this clear enough. Any help would be appreciated.
edit:
In the main program I created an array of Sets.
Set[] sets = new Set[7];
for (int i = 0; i< sets.length; i++) //initialize each element
{
sets[i] = new LinkedListSet();
}
each list has nodes with data values which are added on later on in the code...
then I call the difference method.
sets[0].difference(sets[1], sets[4])
sets[1].isEmpty returns true for some reason (even though it is not).
If I were to do something like:
System.out.println(sets[1].first.data()) I would have no problem whatsoever.
For some reason all the values become null when the parameters are passed to the difference method.
public boolean isEmpty()
{
return first == null;
}
I tested what you are trying to do with the following code and I see no problems:
import org.junit.Test;
public class RandomCastTest {
public interface Set {
boolean isEmpty();
void add(int x);
void difference(Set other, Set result);
#Override
String toString();
#Override
boolean equals(Object other);
}
public class LinkedListSet implements Set {
private class Node //much easier as a private class; don't have to extend
{
private int data;
private Node next;
public Node() {
}
public Node(int x) {
data = x;
}
public int data() {
return data;
}
public Node next() {
return next;
}
public void next(Node node) {
next = node;
}
}
private Node first;
private int Size;
private int whichList; //used to identify the particular LL object
#Override
public boolean isEmpty() {
return first == null;
}
#Override
public void add(int x) {
Node node = new Node(x);
if (first == null) {
first = node;
} else {
Node currentNode;
Node nextNode = first;
do {
currentNode = nextNode;
nextNode = currentNode.next();
} while (nextNode != null);
currentNode.next(node);
}
Size++;
}
#Override
public void difference(Set other, Set result) {
if (other.isEmpty()) {
System.out.println("The set is empty before cast");
}
LinkedListSet othr = (LinkedListSet) other;
LinkedListSet res = (LinkedListSet) result;
if (this.isEmpty() || othr.isEmpty()) {
if (othr.isEmpty())
System.out.println("The set is empty after cast");
if (this.isEmpty())
System.out.println("This is also empty");
return;
}
result = res;
}
}
#Test
public void test() {
Set[] sets = new Set[7];
for (int i = 0; i < sets.length; i++) {
sets[i] = new LinkedListSet();
}
for (int i = 0; i < 5; i++) {
sets[1].add(i);
}
for (int i = 5; i < 10; i++) {
sets[0].add(i);
}
sets[0].difference(sets[1], sets[4]);
// ... find difference
}
}
To simplify I removed unimplemented methods from the interface. Also added the add method implementation. Please see if it works for you.
I have a doubly linked list in my case. And I want to find the max and min element. So I want to use the Collections to find it. Here is my code below for Node first:
public class Node<T> {
Node<T> prev;
Node<T> next;
T data;
public Node(T _data)
{
data = _data;
prev = null;
next = null;
}
public Node(T _data, Node<T> _prev, Node<T> _next)
{
data = _data;
prev = _prev;
next = _next;
}
T getData()
{
return data;
}
public void setNext(Node<T> _next)
{
next = _next;
}
public void setPrev(Node<T> _prev)
{
prev = _prev;
}
public Node<T> getNext()
{
return next;
}
public Node<T> getPrev()
{
return prev;
}
}
And here is my Doubly Linked List class:
public class DoublyLinkedList<T> {
private Node<T> head;
private Node<T> tail;
int listCount = 0;
public void traverseF()
{
Node<T> temp = head;
while(temp != null)
{
System.out.print(temp.getData() + " ");
temp = temp.getNext();
}
}
public void traverseB()
{
Node<T> temp = tail;
while(temp != null)
{
System.out.print(temp.getData() + " ");
temp = temp.getPrev();
}
}
public void insertFirst(T data)
{
Node<T> temp = new Node<T>(data);
if(head == null)
{
head = temp;
tail = temp;
temp.setNext(null);
temp.setPrev(null);
}
else
{
temp.setNext(head);
head.setPrev(temp);
head = temp;
}
}
}
So, my main code is:
import java.util.Collections;
public class glavna {
public static void main(String[] args) {
DoublyLinkedList<Integer> DLL = new DoublyLinkedList<Integer>();
DLL.insertFirst(32);
DLL.insertFirst(22);
DLL.insertFirst(55);
DLL.insertFirst(10);
DLL.traverseF();
Integer max = Collections.max(DLL);
}
}
How exactly do I call the Collections.max or Collections.min method? Isn't the list only necessary to find the max/min elements?
public T getMin()
{
Node<T> temp = head;
T min = head.getData();
while(temp.getNext() != null)
{
if(temp.getData() < min) // error
{
//min = temp.getData();
}
}
}
To implement getMin with generics you need to be able to compare them. You can, for instance, provide a custom Comparator to your method:
public T getMin(Comparator<? super T> comparator) {
Node<T> temp = head.getNext();
T min = head.getData();
while(temp != null) {
T candidateValue = temp.getData();
if (comparator.compare(candidateValue, min) < 0) { // equivalent to candidate < min
min = candidateValue;
}
temp = temp.getNext();
}
return min;
}
Then, calling your method for Integer :
getMin(new Comparator<Integer>() {
#Override
public int compare(Integer arg0, Integer arg1) {
return arg0.compareTo(arg1);
}
});
Another approach is to make your list only keep Comparable items :
public class DoublyLinkedList<T extends Comparable<? super T>> {
and then have your getMin() method use compareTo method :
public T getMin() {
Node<T> temp = head.getNext();
T min = head.getData();
while(temp != null) {
T candidateValue = temp.getData();
if (candidateValue.compareTo(min) < 0) { // equivalent to candidate < min
min = candidateValue;
}
temp = temp.getNext();
}
return min;
}
Second approach is less verbose, as Integer is Comparable (i.e. implements Comparable for you already), so you won't need to change any other code.
You list is not a Collection, so you cannot use Collections with it.
The Collections.max method expects an argument which implements Collection. The easiest way would probably be to extend AbstractCollection and add these methods:
#Override
public Iterator<T> iterator() {
return new Iterator<T>() {
private Node<T> node = head;
#Override
public boolean hasNext() {
return node != null;
}
#Override
public T next() {
T next = node.data;
node = node.getNext();
return next;
}
};
}
#Override
public int size() {
int size = 0;
Node<T> node = head;
while (node != null) {
size++;
node = node.getNext();
}
return size;
}