So I recently learnt about Generics and thought it would be cool to implement them in a Priority Queue. I am having a "Block" element which has a firstName and a data variable. The Node for the Priority Queue consists of Block, Next and Prev.
I am attaching the code below. I am almost exclusively getting "Should be parametrized" errors/warnings. And an error which says that my "Data" element cannot be resolved to a field, which probably means that I am unable to tell that I want Block as my "element E" in a Node. Any suggestions will be deeply appreciated
package QGen;
public class Block<E> implements Comparable<Block<E>> {
protected String firstName;
protected int data;
public Block(String firstName, int data) {
super();
this.firstName = firstName;
this.data = data;
}
#Override
public int compareTo(Block x) {
return (this.data - x.data);
}
}
package QGen;
public class PriorityQueue<E extends Comparable> {
protected Node<E> firstSentinel;
protected Node<E> lastSentinel;
protected class Node<E> {
protected Node<E> next;
protected Node<E> prev;
private E element;
public Node(E e, Node<E> previous, Node<E> nextt) {
element = e;
prev = previous;
next = nextt;
}
}
public PriorityQueue() {
firstSentinel = new Node<>(null, null, null);
lastSentinel = new Node<>(null, null, null);
firstSentinel.data = 11111;
lastSentinel.data = 0;
firstSentinel.prev = null;
firstSentinel.next = lastSentinel;
lastSentinel.prev = firstSentinel;
lastSentinel.next = null;
}
public void enQueue(E x) {
Node<E> newX = new Node<E>(x, null, null);
if (firstSentinel.next == lastSentinel)// list is empyty
{
firstSentinel.next = newX;
newX.prev = firstSentinel;
newX.next = lastSentinel;
lastSentinel.prev = newX;
} else {
Node<E> temp = newX;
Node<E> curr = firstSentinel.next;
while (curr != lastSentinel && temp.element.compareTo(curr) <= 0) {// <=comparison
// replaced
curr = curr.next;
}
Node<E> tempCurr = curr;
temp.next = tempCurr;
temp.prev = tempCurr.prev;
tempCurr.prev.next = temp;
tempCurr.prev = temp;
}
}
public E deQueue() {
if (firstSentinel.next == lastSentinel) {
return null;
} else {
Node<E> temp = new Node<E>(null, null, null);
temp = firstSentinel.next;
firstSentinel.next = temp.next;
temp.next.prev = firstSentinel;
return temp.element;
}
}
public void printt() {
Node<E> temp = new Node<E>(null, null, null);
temp = firstSentinel.next;
while (temp != lastSentinel) {
System.out
.println(temp.element.firstName + " " + temp.element.data);
temp = temp.next;
}
}
}
package QGen;
public class containsMain<E> {
public static void main(String[] args) {
PriorityQueue<Block> example = new PriorityQueue<Block>();
Block dequedObject = new Block<>(null, null);
Block<Block> incomingName = new Block<>("r", 1);
example.enQueue(incomingName);
dequedObject = (Block) example.deQueue();
}
}
I am aware that my PriorityQueue might not be the best of implementations and I will improve it. It is the Generics where I am unable to come up with a solution
Thanks
Without looking at the logic of your methods, I have several remarks regarding generics:
why is Block itself generic? It doesnt hold any generic field so remove it from Block!
new Node<>(null, null, null);
// this is a bad idea, change it to new Node<E>(null, null, null)
firstSentinel.data = 11111;
lastSentinel.data = 0;
//Those two cant work, because firstSentinel is referencing a Node<E> and not a Block! Delete those two rows, as they make no sense in your generic implementation of the Queue
Block<Block> incomingName = new Block<>("r", 1);
// This doesnt make sense, should be Block incomingName = new Block(...)
Related
I've managed to make the doubly linked list into a circular one, I'm just having trouble making a method to remove the first element. I've tried looking at examples for single linked lists but I can't seem to modify it to fit my code. Any help would be greatly appreciated.
Linkedlist Class
package LinkedListS;
public class LinkedList {
private Node first;
private Node end;
LinkedList()
{
first = end = null;
}
public void addAtStart(int x){
Node temp = new Node(x);
if(first == null)
{
first = end = temp;
}
else
{
end.setNext(temp);
temp.setNext(first);
first = temp;
}
}
public void printFromStart()
{
Node temp = first;
do {
System.out.println(temp.getData());
temp = temp.getNext();
end.setNext(null);
} while (temp != null);
}
public void searchFromStart(int elementToBeSearched)
{
Node temp = first;
while(temp != null)
{
if (temp.getData() == elementToBeSearched)
{
System.out.println("Found " + elementToBeSearched);
return;
}
temp = temp.getNext();
}
System.out.println("Didn't find " + elementToBeSearched);
}
public void removeFirstElement(){
}
Driver Class:
enter code here
public class LinkedListMain {
public static void main(String[] args) {
LinkedList ll = new LinkedList();
System.out.println("Going to add elements At Start");
ll.addAtStart(5);
ll.addAtStart(7);
ll.addAtStart(9);
ll.addAtStart(10);
System.out.println("Print the doubly linked list elements");
ll.printFromStart();
System.out.println("Search the following elements");
ll.searchFromStart(7);
ll.searchFromStart(1289);
ll.removeFirstElement();
ll.printFromStart();
}
}
Node Class:
package LinkedListS;
public class Node {
private int data;
private Node next;
private Node prev;
// Constructor to intialize/fill data
public Node(int data)
{
this.data = data;
}
// set the address of next node
public void setNext(Node temp)
{
this.next = temp;
}
// get the address of next node
public Node getNext()
{
return this.next;
}
public Node getPrev()
{
return this.prev;
}
public void setPrev(Node temp)
{
this.prev = temp;
}
// to get data of current node
public int getData()
{
return this.data;
}
}
For the removeFirstElement method I've tried these solutions with no avail:
Attempt #1
Node temp = first;
temp = null;
Attempt #2
Node temp = first;
if(first != null){
if(temp.getNext() == first){
first = null;
}
} else {
first = end;
end = first.getNext();
}
Attempt #3
Node temp = first;
if (first == null) {
System.out.println("There is no first element to remove");
} else
temp = first;
System.out.println(temp);
Attempt #4
Node temp = first;
end = null;
if(first != null){
if(temp.getNext() == temp){
first = null;
}
} else {
end = first;
first = first.getNext();
}
After scanning a few other methods that is what I found that works:
public void removeFirstElement(){
if (first != null){
first = first.getNext();
} else {
System.out.println("There is nothing to be removed");
}
}
I am trying to insert a node at the end of doubly linked list but when I run the add method, the code never finishes running. Here is the code below:
public class DoublyLinkedList<T> {
static class Node<T> {
T data;
Node<T> next;
Node<T> previous;
Node() {
data = null;
next = null;
previous = null;
}
Node(T value) {
data = value;
next = null;
previous = null;
}
}
private Node<T> head;
private int size;
public DoublyLinkedList() {
head = null;
}
public DoublyLinkedList(T value) {
head = new Node<T>(value);
size ++;
}
public void add(T value) {
Node<T> append = new Node<T>(value);
append.next = null;
if(head == null) {
append.previous = null;
head = append;
size ++;
return;
}
Node current = head;
while(current.next != null) {
current = current.next;
}
current.next = append;
append.previous = current;
size ++;
}
I pretty sure the line that says current.next = append is the problem, but I am not sure how to fix it. What am I doing wrong?
I've been struggling with implementing a Binary Search Tree with the Iterator method. I've been checking out this algorithm out on WikiPedia:
def search_recursively(key, node):
if node is None or node.key == key:
return node
if key < node.key:
return search_recursively(key, node.left)
# key > node.key
return search_recursively(key, node.right)
I translated it to Java:
public Iterator<T> iterator()
{
return new Iterator<T>()
{
private int count = 0;
#Override
public boolean hasNext()
{
return count++ < size;
}
#Override
public T next()
{
return search(root, root.word);
}
public T search(BST root, T word)
{
if (root == null || root.word.compareTo(word) == 0)
{
return root.word;
}
if (root.word.compareTo(word) < 0)
{
return search(root.left, word);
}
return search(root.right, word);
}
};
When trying to run the program I only get the root element of the BST:
MyWordSet bst = new MyWordSet();
T bst = new T("one");
T bst = new T("two");
T bst = new T("three");
T bst = new T("four");
T bst = new T("five");
T bst = new T("six");
bst.add(w1);
bst.add(w2);
bst.add(w3);
bst.add(w4);
bst.add(w5);
bst.add(w6);
Iterator<T> it = bst.iterator();
while (it.hasNext())
{
System.out.println(it.next());
}
So the output is:
one
one
one
one
one
one
So why does this method inside my Iterator not work for me to get to the whole tree? I really can't figure out what is wrong here and why it only prints out one when it should go down the tree.
You simply do not update the current_node.
The equivalent of current_node = node is missing.
Well, after having changed the code, here revised answer:
import java.util.Iterator;
import java.util.Stack;
/**
*
* #author jk
*/
public class BSTIterator<T> implements Iterator<T> {
public static final class BST<T> {
private BST<T> left;
private BST<T> right;
private T word;
private BST(T word) {
this.word = word;
}
}
private final Stack<BST<T>> stackBST = new Stack<>();
public BSTIterator(final BST<T> root) {
// push all most left entries of the tree to the stack
BST<T> currBST = root;
while (currBST != null) {
stackBST.push(currBST);
currBST = currBST.left;
}
}
#Override
public boolean hasNext() {
return !stackBST.isEmpty();
}
#Override
public T next() {
BST<T> currBST = stackBST.pop();
// check if we are on the most right entry
final boolean notMostRightEntry = currBST.right != null;
if (notMostRightEntry) {
// take next right entry
BST<T> nextBST = currBST.right;
while (nextBST != null) {
// push this next right entry on the stack
stackBST.push(nextBST);
nextBST = nextBST.left;
}
}
return currBST.word;
}
public static void main(String[] args) {
BST<Integer> root = new BST<>(20);
root.left = new BST<>(5);
root.right = new BST<>(30);
root.left.right = new BST<>(10);
root.right.left = new BST<>(25);
root.right.right = new BST<>(40);
root.right.left = new BST<>(35);
root.right.left.left = new BST<>(32);
for (Iterator<Integer> bstIt = new BSTIterator<>(root); bstIt.hasNext();) {
System.out.println("val: " + bstIt.next());
}
}
}
I was trying to do the deep copy of my linked list known as DictionaryNode which I did but i was not able to display it's content in display method as it is always null. why DictinaryNode temp is always null ? and if i try to assign temp = head work but with temp = copy doesn't.
public class ListOfNodes {
public class DictionaryNode {
protected String word;
private int level;
private DictionaryNode next;
private int space = 0;
public void displayCopy() {
DictionaryNode temp = copy.next;
while( temp != null ) {
System.out.println(temp.word)
temp = temp.next;
}
}
public DictionaryNode( String word, int level ) {
this.word = word;
this.level = level;
next = null;
}
}
private DictionaryNode head = null;
public DictionaryNode copy = null;
//used to do deep copy
public void Clone() {
DictionaryNode temp = head.next;
while( temp != null ) {
copy = new DictionaryNode( temp.word , temp.level );
copy = copy.next;
temp = temp.next;
}
}
public void displayCopy() {
DictionaryNode temp = copy.next;
while( temp != null ) {
Sytem.out.println(temp.word)
temp = temp.next;
}
}
This program will demonstrate how to do a deep copy on a list. It's more generic than your specific example so hopefully it helps others too.
public class Java_Practice {
private static class LinkedListTest {
private String data;
private LinkedListTest next;
public LinkedListTest(String data) {
super();
this.data = data;
}
public String getData() {
return data;
}
public LinkedListTest getNext() {
return next;
}
public void setNext(LinkedListTest next) {
this.next = next;
}
#Override
public String toString() {
return "LinkedListTest [data=" + data + ", next=" + next + "]";
}
}
// Do a deep copy
private static LinkedListTest copyLlt(LinkedListTest original) {
LinkedListTest copy = new LinkedListTest(original.getData() + " copied");
LinkedListTest nextCopy = original.getNext();
LinkedListTest current = copy;
while (nextCopy != null) {
LinkedListTest newCopy = new LinkedListTest(nextCopy.getData() + " copied");
newCopy.setNext(nextCopy.getNext());
current.setNext(newCopy);
current = newCopy;
nextCopy = newCopy.getNext();
}
return copy;
}
public static void main(String[] args) {
LinkedListTest firstLlt = new LinkedListTest("First");
LinkedListTest secondLlt = new LinkedListTest("Second");
LinkedListTest thirdLlt = new LinkedListTest("Thrid");
firstLlt.setNext(secondLlt);
secondLlt.setNext(thirdLlt);
LinkedListTest copiedLlt = copyLlt(firstLlt);
// Data should say First, Second, Third
System.out.println("Original LinkedListTest: " + firstLlt.toString());
// Data should say First Copied, Second Copied, Third Copied
System.out.println("Copied LinkedListTest: " + copiedLlt.toString());
}
}
In your Clone method you never assign a next field for the copied content. You need to do this to have more than a single connected node in the copy. Furthermore you need to copy the head too. Moreover do must not overwrite copy with anything but the copy of the head:
copy = new DictionaryNode(null, head.level);
DictionaryNode temp = head.next;
DictionaryNode current = copy;
while( temp != null) {
DictionaryNode nn = new DictionaryNode( temp.word , temp.level);
current.next = nn;
current = nn;
temp = temp.next;
}
So i have implemented the insert method and it works just fine but my problem is how to check whether a member is already in the list or not,i want the program to check if the member is already in the list but the checker doesn't work. i want the program to put the member in team1 if the member is included in the list and Display "member does not exist" if the member is not on the list. I made a check method but it doesn't work. I am new in Programming and i really need help. Please enlighten me with your knowledge.
class Node
{
protected String info;
protected Node next;
public Node(String value)
{
info = value;
next = null;
}
}
class LinkedList
{
private Node head;
private int count;
public LinkedList()
{
head = null;
count = 0;
}
public void insert( String name)
{
Node a = new Node(name);
a.next = null;
count++;
if (head == null)
{
head = a;
return;
}
for(Node cur = head; cur != null; cur = cur.next)
{
if (cur.next == null)
{
cur.next = a;
return;
}
}
}
public void checker(String name)
{
for(Node cur = head; cur != null; cur = cur.next)
{
if(cur.info == name)
{
insertteam1(name);
System.out.print("OK");
}
else
{
System.out.print("member does not exist");
}
}
}
public void insertteam1(String name)
{
Node b = new Node(name);
b.next = null;
count++;
if (head == null)
{
head = b;
return;
}
for(Node cur = head; cur != null; cur = cur.next)
{
if (cur.next == null)
{
cur.next = b;
return;
}
}
}
In the code below,
if(cur.info == name){ // }
you are comparing the string info using == which is not the right way to compare strings in java.
Use
if(cur.info.equals(name)){ // }
or
use if(cur.info.equalsIgnoreCase(name)){ // } if you want to do case insensitive compare.