RadixSort Null pointer [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
Can someone take a look at my Radix sort code and help me figure out how i can properly enque the new entry? Because as of right now the way i did it seems to never be able to set a second entry... It always points it as a null for some reason. I tried to set the tempNode to = new Node(newEntry) then just set the next constalty to null if its not defined but that still did not work.
class LinkedQueue<T> implements QueueInterface<T> {
private Node start;
private Node end;
public LinkedQueue() {
start = null;
end = null;
}
#Override
public void enqueue(T newEntry) {
Node tempNode = new Node(newEntry, null);
if (isEmpty()) {
start = tempNode;
} else {
end.setNext(tempNode);
end = tempNode;
}
}
#Override
public T dequeue() {
T front = null;
if (!isEmpty()) {
front = start.getData();
start = start.getNext();
if (start == null) // verification purposes
end = null;
}
return front;
}
#Override
public T getFront() {
T front = null;
if (!isEmpty())
front = start.getData();
return front;
}
#Override
public boolean isEmpty() {
return (start == null && end == null);
}
// reset the list
#Override
public void clear() {
start = null;
end = null;
}
private class Node {
private T data;
private Node next;
public Node(T data) {
this.data = data;
next = null;
}
public Node(T data, Node next) {
this.data = data;
this.next = next;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
}
}
public class RadixSorting {
public static final int MAX = 10;
public static void radixSort(int[] myArray, int start, int last, int maxDigit) {
#SuppressWarnings("unchecked")
QueueInterface<Integer>[] buckets = new LinkedQueue[MAX];
System.out.println("\n");
System.out.println("Buckets size:" + buckets.length);
int bucket;
int index;
int i;
for (bucket = 0; bucket < MAX; bucket++)
buckets[bucket] = new LinkedQueue<Integer>();
int multiplier = 1;
for (i = 1; i <= maxDigit; i++, multiplier *= MAX) {
for (bucket = 0; bucket < MAX; bucket++)
buckets[bucket].clear();
for (index = start; index <= last; index++) {
int tempNum = (myArray[index] % (multiplier * MAX)) / multiplier;
buckets[tempNum].enqueue(myArray[index]);
}
bucket = 0;
for (index = start; index <= last; index++) {
while (buckets[bucket].isEmpty())
bucket++;
myArray[index] = buckets[bucket].dequeue();
}
}
}
public static void main(String args[]) {
int array[] = { 5, 50, 15, 45, 40, 10, 25, 30, 20, 35 };
RadixSorting.radixSort(array, 0, array.length -1, 4);
}
}
Heres my error:
Exception in thread "main" java.lang.NullPointerException
at week5.LinkedQueue.enqueue(RadixSorting.java:51)
at week5.RadixSorting.radixSort(RadixSorting.java:143)
at week5.RadixSorting.main(RadixSorting.java:157)

I solved it, i managed to debug it with a fresh mind and i saw the answers.

Related

Interval search in Binary Tree

Can someone help me with the interval search in binary tree.
I understand how to check left side of the tree,but I have troubles with chicking right side of it.
This is my code by now.
private boolean search(BSTNode r, int from,int till){
boolean found = false;
int arr[];
arr=new int[10];
int i=0;
while (r != null)
{
int rval = r.getData();
if (from < rval && till >rval) {
r = r.getLeft();
arr[i]=rval;
i++;
}else
r=r.getRight();
}
return found;
}
This is full class of BSTNode.
From and till it is range of interval(from
class BSTNode
{
BSTNode left, right;
int data;
/* Constructor */
public BSTNode()
{
left = null;
right = null;
data = 0;
}
/* Constructor */
public BSTNode(int n)
{
left = null;
right = null;
data = n;
}
/* Function to set left node */
public void setLeft(BSTNode n)
{
left = n;
}
/* Function to set right node */
public void setRight(BSTNode n)
{
right = n;
}
/* Function to get left node */
public BSTNode getLeft()
{
return left;
}
/* Function to get right node */
public BSTNode getRight()
{
return right;
}
You can search by using queue like this:
public boolean search(Integer from, Integer till) {
return search(root, from, till);
}
private boolean search(BSTNode root, Integer from, Integer till) {
boolean found = false;
Queue<BSTNode> queue = new ArrayDeque<>();
queue.add(root);
List<Integer> list = new ArrayList<>();
while (!queue.isEmpty()) {
BSTNode node = queue.poll();
int data = node.getData();
if (from < data && till > data) {
found = true;
list.add(data);
}
if (node.getLeft() != null)
queue.add(node.getLeft());
if (node.getRight() != null)
queue.add(node.getRight());
}
System.out.println(list);
return found;
}
, full code
public static void main(String[] args) {
BinarySearchTree tree = new BinarySearchTree();
// Tree building...
tree.insert(50);
tree.insert(40);
tree.insert(20);
tree.insert(10);
tree.insert(50);
System.out.println(tree.search(10, 30));
}
static class BinarySearchTree {
private BSTNode root;
public void insert(Integer item) {
root = insert(root, item);
}
private BSTNode insert(BSTNode node, Integer item) {
if (node == null) {
return new BSTNode(item);
} else if (item.compareTo(node.data) == 0) {
return node;
} else if (item.compareTo(node.data) < 0) {
node.setRight(insert(node.r, item));
return node;
} else {
node.setLeft(insert(node.l, item));
return node;
}
}
public Integer find(Integer target) {
return find(root, target);
}
private Integer find(BSTNode node, Integer target) {
if (node == null) {
return null;
}
Integer cmd = target.compareTo(node.data);
if (cmd == 0) {
return node.data;
} else if (cmd < 0) {
return find(node.getRight(), target);
} else {
return find(node.getLeft(), target);
}
}
public boolean search(Integer from, Integer till) {
return search(root, from, till);
}
private boolean search(BSTNode root, Integer from, Integer till) {
boolean found = false;
Queue<BSTNode> queue = new ArrayDeque<>();
queue.add(root);
List<Integer> list = new ArrayList<>();
while (!queue.isEmpty()) {
BSTNode node = queue.poll();
int data = node.getData();
if (from < data && till > data) {
found = true;
list.add(data);
}
if (node.getLeft() != null)
queue.add(node.getLeft());
if (node.getRight() != null)
queue.add(node.getRight());
}
System.out.println(list);
return found;
}
}
static class BSTNode {
Integer data;
BSTNode l = null;
BSTNode r = null;
public BSTNode(Integer data) {
super();
this.data = data;
}
public Integer getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
public BSTNode getLeft() {
return l;
}
public void setLeft(BSTNode l) {
this.l = l;
}
public BSTNode getRight() {
return r;
}
public void setRight(BSTNode r) {
this.r = r;
}
#Override
public String toString() {
return "BSTNode [data=" + data + ", l=" + l + ", r=" + r + "]";
}
}
, the output
[20]
true

Queue reverse implementation - code not working

I'm new to programming and trying to implement an algorithm which reverse K elements in a queue using linkedlist and stack but for some reason, I'm not able to execute the algorithm, any help is greatly appreciated.
I found queue is coming as empty eventhough I add values to it & I see added values in console but when I checked queue.isEmpty() is coming as true.
Here is my code
public class QueueReverseK {
public void reverse(QueueADT queue, int k) {
if (queue.isEmpty()) {
System.out.println("in if empty");
return;
}
if (k > queue.size()) {
k = queue.size;
} else if (k < 0) {
k = 0;
}
StackADT tempStack = new StackADT(k);
QueueADT newQueue = new QueueADT();
for (int i = 0; i < k; i++) {
tempStack.push(queue.deQueue().getData());
}
while (!tempStack.isEmpty()) {
newQueue.enQueue(tempStack.pop());
}
while (!queue.isEmpty()) {
newQueue.enQueue(queue.deQueue().getData());
}
queue = newQueue;
}
Queue class
public class Queue {
LinkedList items;
int size;
Node head;
Node tail;
LinkedListADT list = new LinkedListADT();
public Queue() {
items = new LinkedList();
size = 0;
head = null;
tail = null;
}
public int size() {
return size;
}
public boolean isEmpty() {
if (head == null) return true;
else return false;
}
public void enQueue(int i) {
items.addHead(i);
}
public Node deQueue() {
return items.deleteHead();
}
public void printQueue() {
items.printList();
}
}
LinkedList Class
public class LinkedList {
Node head;
Node tail;
LinkedList() {
head = null;
tail = null;
}
public void addHead(int val) {
Node n = new Node(val);
if (head == null) {
head = n;
tail = n;
} else {
Node tempNode = head;
while (tempNode.next != null) {
tempNode = tempNode.next;
}
tempNode.next = n;
}
}
public void addTail(int val) {
Node n = new Node(val);
if (head == null) {
head = n;
tail = n;
} else {
tail.next = n;
tail = n;
}
}
public int deleteTail() {
Node n = tail;
if (head == null) {
return -1;
} else if (head == tail) {
head = null;
tail = null;
} else {
Node cur = head;
while (cur.getNext() != tail)
cur = cur.next;
tail = cur;
tail.next = null;
}
return n.getData();
}
public Node deleteHead() {
Node n = head;
head = head.next;
return n;
}
public int count() {
int size = 0;
Node n = head;
while (n != null) {
n = n.getNext();
size++;
}
return size;
}
public Node getHead() {
return head;
}
public void setHead(Node head) {
this.head = head;
}
public Node getTail() {
return tail;
}
public void setTail(Node tail) {
this.tail = tail;
}
public void printList() {
if (this.head == null) {
return;
}
// print all nodes
Node tempNode = this.head;
while (tempNode != null) {
System.out.print(tempNode.data + "->");
tempNode = tempNode.next;
}
}
void printMiddle(int n) {
Node slow_ptr = head;
Node fast_ptr = head;
if (head != null) {
while (fast_ptr != null && fast_ptr.next != null) {
fast_ptr = fast_ptr.next.next;
slow_ptr = slow_ptr.next;
}
System.out.print(slow_ptr.data + " ");
for (int i = 1; i <= n && slow_ptr != null; i++) {
slow_ptr = slow_ptr.next;
System.out.print(slow_ptr.data + " ");
}
}
}
}
Main Class
public static void main(String[] args) {
Queue Q = new Queue();
Q.enQueue(1);
Q.enQueue(2);
Q.enQueue(3);
Q.enQueue(4);
QueueReverseK k = new QueueReverseK();
k.reverse(Q, 2)
Q.printQueue();
}
Stack Class
public class Stack {
private int top;
private int items[];
private int max;
public StackADT(int n) {
this.max = n;
top = 0;
items = new int[n];
}
public boolean isEmpty() {
return top == 0;
}
public boolean isFull() {
return top == max;
}
public void push(int item) {
if (isFull()) throw new IllegalArgumentException();
else items[top++] = item;
}
public int pop() {
if (isEmpty()) throw new IllegalArgumentException();
else return items[--top];
}
public int size() {
return top;
}
}
}
Example
input Queue: 12 34 65 76 23 12 36 90
output Queue : 12 34 65 76 90 36 12 23
I'm not entirely positive, but it looks like your queue is acting like a stack. You're enQueue is pushing to the head, not the tail of the queue.

How to manage Heap (Min heap) if the value of already added item changes

I am a java developer ( but from a NON CS/IT educational background). I have developed interest in algorithms and currently I am trying to implement Prim's Algorithm for Calculating MST. This I have told in order to let you know the context but my question is independent of MST.
I have implemented my own MinHeap instead of using Java.util.PriorityQueue (although even when I changed my code and used it I was facing the same problem that I have mentioned ahead).
I add items to the heap but the value of the item deciding the comparison can change even after the items have been added in the heap. Now once the value changes the heap is not changed and hence upon removing the item I get wrong item popped out.
How to tackle this situation..
I am pasting my code for reference. I am adding items of type Vertex in my MinHeap. Each Vertex has an 'int cost' associated which is used to compare two objects of Vertex. Now I add object of Vertex in the heap and heap is adjusted as per current value of 'cost' but once an object of Vertex is added then if its cost is changed then I want help as how to adjust and get it reflected in my Heap. Please help me in this regards and also please correct me if I am going in wrong direction.
public class MSTRevisited {
public static void main(String[] args) {
Graph graph = new Graph(6);
graph.addNode('a');
graph.addNode('b');
graph.addNode('c');
graph.addNode('d');
graph.addNode('e');
graph.addNode('f');
graph.addEdege('a', 'b', 4);
graph.addEdege('a', 'f', 2);
graph.addEdege('b', 'f', 3);
graph.addEdege('b', 'c', 6);
graph.addEdege('c', 'f', 1);
graph.addEdege('c', 'd', 3);
graph.addEdege('d', 'e', 2);
graph.addEdege('f', 'e', 4);
graph.applyPrimAlgo();
}
public static class Graph {
private Vertex verticies[];
private int maxSize;
private int size;
private HashMap map;
private MinHeap Q;
public Graph(int maxSize) {
this.maxSize = maxSize;
verticies = new Vertex[maxSize];
map = new HashMap(maxSize);
Q = new MinHeap(maxSize);
}
public void addNode(char data) {
verticies[size] = new Vertex(data, size);
map.put(data, size);
size++;
}
public void addEdege(char sourceData, char destinationData, int weight) {
int sourceIndex = map.get(sourceData);
int destinationIndex = map.get(destinationData);
verticies[sourceIndex].adj = new Neighbour(destinationIndex, weight,
verticies[sourceIndex].adj);
verticies[destinationIndex].adj = new Neighbour(sourceIndex,weight,
verticies[destinationIndex].adj);
}
public void applyPrimAlgo() {
// add all the keys to the Q
PrimEdege pe = null;
Vertex vertex = verticies[0];
vertex.cost = 0;
vertex.state = Vertex.IN_Q;
Q.add(vertex);
while(!Q.isEmpty()){
Vertex poppedVertex = Q.remove();
poppedVertex.state = Vertex.VISITED;
Neighbour temp = poppedVertex.adj;
while(temp != null){
Vertex adjVertex = verticies[temp.index];
if(adjVertex.state != Vertex.VISITED){
if(poppedVertex.parentIndex != -1){
char source = verticies[poppedVertex.index].data;
char destination = verticies[adjVertex.index].data;
pe = new PrimEdege(source, destination, pe);
}
if(adjVertex.cost > temp.weight){
adjVertex.cost = temp.weight;
adjVertex.parentIndex = poppedVertex.index;
}
if(adjVertex.state != Vertex.IN_Q){
Q.add(adjVertex);
}
}
temp = temp.next;
}
}
PrimEdege temp = pe;
while(temp != null){
System.out.print("("+temp.source+","+temp.destination+") ");
temp = temp.next;
}
System.out.println();
}
private static class PrimEdege{
public char source;
public char destination;
private PrimEdege next;
public PrimEdege(char source, char destination, PrimEdege next){
this.source = source;
this.destination = destination;
this.next = next;
}
}
public static class MinHeap {
private Vertex[] items;
private int maxSize;
private int size;
public MinHeap(int maxSize) {
this.maxSize = maxSize;
items = new Vertex[maxSize];
}
public void add(Vertex item) {
items[size] = item;
heapifyAfterAdd();
size++;
}
private void swap(int index1, int index2) {
Vertex temp = items[index1];
items[index1] = items[index2];
items[index2] = temp;
}
private void heapifyAfterAdd() {
int currIndex = size;
Vertex currItem = items[currIndex];
int parentIndex = currIndex / 2;
Vertex parentItem = items[parentIndex];
while (currItem.compareTo(parentItem) == -1) {
swap(parentIndex, currIndex);
currIndex = parentIndex;
currItem = items[currIndex];
parentIndex = currIndex / 2;
parentItem = items[parentIndex];
}
}
public Vertex remove() {
Vertex vertex = items[0];
swap(0, size - 1);
items[size-1] = null;
size--;
heapifyAfterRemove();
return vertex;
}
private void heapifyAfterRemove() {
int currIndex = 0;
Vertex currItem = items[currIndex];
int childIndex;
Vertex childItem;
int left = 2 * currIndex + 1;
int right = 2 * currIndex + 2;
if (left > size - 1) {
return;
}
if (right > size - 1) {
childIndex = left;
} else if (items[left].compareTo(items[right]) == -1) {
childIndex = left;
} else {
childIndex = right;
}
childItem = items[childIndex];
while (childItem.compareTo(currItem) == -1) {
swap(currIndex, childIndex);
currIndex = childIndex;
currItem = items[currIndex];
left = 2 * currIndex + 1;
right = 2 * currIndex + 2;
if (left > size - 1) {
return;
}
if (right > size - 1) {
childIndex = left;
} else if (items[left].compareTo(items[right]) == -1) {
childIndex = left;
} else {
childIndex = right;
}
childItem = items[childIndex];
}
}
public boolean isEmpty() {
return size == 0;
}
}
public static class HashMap {
private MapNode[] map;
private char[] keySet;
private int maxSize;
private int size;
public HashMap(int maxSize) {
this.maxSize = maxSize;
map = new MapNode[maxSize];
keySet = new char[maxSize];
}
private static class MapNode {
char key;
int value;
MapNode next;
public MapNode(char key, int value, MapNode next) {
this.key = key;
this.value = value;
this.next = next;
}
}
public int hash(char key) {
return 31 * key;
}
public int getmapIndexOfkey(char key) {
return hash(key) % maxSize;
}
public void put(char key, int value) {
int index = getmapIndexOfkey(key);
map[index] = new MapNode(key, value, map[index]);
keySet[index] = key;
size++;
}
public int get(char key) {
int index = getmapIndexOfkey(key);
MapNode temp = map[index];
while (temp != null) {
if (temp.key == key) {
break;
}
}
if (temp != null) {
return temp.value;
} else {
return -1;
}
}
public char[] keyset() {
return keySet;
}
}
public static class Vertex {
public static final int NEW = 0;
public static final int IN_Q = 1;
public static final int VISITED = 2;
private int state = NEW;
private int cost = Integer.MAX_VALUE;
private char data;
private Neighbour adj;
private int index;
private int parentIndex = -1;
public int compareTo(Vertex other) {
if (cost < other.cost) {
return -1;
}
if (cost > other.cost) {
return 1;
}
return 0;
}
public Vertex(char data, int index) {
this.data = data;
this.index = index;
}
public void addAdjacentVertex(Neighbour adj) {
this.adj = adj;
}
public void updateCost(int newCost, int parentIndex){
this.cost = newCost;
this.parentIndex = parentIndex;
}
}
public static class Neighbour {
private Neighbour next;
private int index;
private int weight;
public Neighbour(int index,int weight, Neighbour next) {
this.next = next;
this.index = index;
this.weight = weight;
}
}
}
}
Thanks friends for investing time to my question, but I figured that I had few mistakes in my implementation due to which I was getting wrong answer.
I corrected the state of the vertex when it is added to the MinHeap
I corrected the logic of outputting the edge of MST and I got the correct answer....
Most important as Suggested by Karthik (many thanks to him) to remove and re-add the item whose 'cost' changes while it being in the heap. I actually applied bubble up approach instead of removing and again adding which worked !!
After modifying above 3 points my code is working as I expect it to work.
Also #Karthik I do not have two methods for before and after remove but rather I have one for when I add an item ( in the last and I use the method heapifyAfterAdd() and other for when I remove the 1st item then I use heapifyAfterRemove() )
Please find below my code after corrections.
public class MSTRevisited {
public static void main(String[] args) {
Graph graph = new Graph(6);
/*
* graph.addNode('a'); graph.addNode('b'); graph.addNode('c');
* graph.addNode('d'); graph.addNode('e'); graph.addNode('f');
* graph.addEdege('a', 'b', 4); graph.addEdege('a', 'f', 2);
* graph.addEdege('b', 'f', 3); graph.addEdege('b', 'c', 6);
* graph.addEdege('c', 'f', 1); graph.addEdege('c', 'd', 3);
* graph.addEdege('d', 'e', 2); graph.addEdege('f', 'e', 4);
*/
graph.addNode('a');
graph.addNode('b');
graph.addNode('c');
graph.addNode('d');
graph.addEdege('a', 'b', 4);
graph.addEdege('a', 'c', 2);
graph.addEdege('b', 'c', 1);
graph.addEdege('b', 'd', 2);
graph.addEdege('c', 'd', 3);
graph.applyPrimAlgo();
}
public static class Graph {
private Vertex verticies[];
private int maxSize;
private int size;
private HashMap map;
private MinHeap Q;
public Graph(int maxSize) {
this.maxSize = maxSize;
verticies = new Vertex[maxSize];
map = new HashMap(maxSize);
Q = new MinHeap(maxSize);
}
public void addNode(char data) {
verticies[size] = new Vertex(data, size);
map.put(data, size);
size++;
}
public void addEdege(char sourceData, char destinationData, int weight) {
int sourceIndex = map.get(sourceData);
int destinationIndex = map.get(destinationData);
verticies[sourceIndex].adj = new Neighbour(destinationIndex,
weight, verticies[sourceIndex].adj);
verticies[destinationIndex].adj = new Neighbour(sourceIndex,
weight, verticies[destinationIndex].adj);
}
public void applyPrimAlgo() {
// add all the keys to the Q
PrimEdege pe = null;
Vertex vertex = verticies[0];
vertex.cost = 0;
vertex.state = Vertex.IN_Q;
Q.add(vertex);
while (!Q.isEmpty()) {
Vertex poppedVertex = Q.remove();
poppedVertex.state = Vertex.VISITED;
Neighbour temp = poppedVertex.adj;
if (poppedVertex.parentIndex != -1) {
char source = verticies[poppedVertex.index].data;
char destination = verticies[poppedVertex.parentIndex].data;
pe = new PrimEdege(source, destination, pe);
}
while (temp != null) {
Vertex adjVertex = verticies[temp.index];
if (adjVertex.state != Vertex.VISITED) {
if (adjVertex.cost > temp.weight) {
adjVertex.cost = temp.weight;
adjVertex.parentIndex = poppedVertex.index;
}
if (adjVertex.state != Vertex.IN_Q) {
Q.add(adjVertex);
adjVertex.state = Vertex.IN_Q;
} else {
// bubble up this Node in the heap
Q.bubbleUp(adjVertex);
}
}
temp = temp.next;
}
}
PrimEdege temp = pe;
while (temp != null) {
System.out.print("(" + temp.source + "," + temp.destination
+ ") ");
temp = temp.next;
}
System.out.println();
}
private static class PrimEdege {
public char source;
public char destination;
private PrimEdege next;
public PrimEdege(char source, char destination, PrimEdege next) {
this.source = source;
this.destination = destination;
this.next = next;
}
}
public static class MinHeap {
private Vertex[] items;
private int maxSize;
private int size;
public MinHeap(int maxSize) {
this.maxSize = maxSize;
items = new Vertex[maxSize];
}
public void bubbleUp(Vertex vertex) {
// #TODO
int i = 0;
for (; i < size; i++) {
if (items[i] == vertex) {
break;
}
}
if (i < size) {
int currentIndex = i;
Vertex currentItem = items[currentIndex];
int parentIndex = (currentIndex-1) / 2;
Vertex parentItem = items[parentIndex];
while (currentItem.compareTo(parentItem) == -1) {
swap(currentIndex, parentIndex);
currentIndex = parentIndex;
currentItem = items[currentIndex];
parentIndex = (currentIndex-1) / 2;
parentItem = items[parentIndex];
}
}
}
public void add(Vertex item) {
items[size] = item;
heapifyAfterAdd();
size++;
}
private void swap(int index1, int index2) {
Vertex temp = items[index1];
items[index1] = items[index2];
items[index2] = temp;
}
private void heapifyAfterAdd() {
int currIndex = size;
Vertex currItem = items[currIndex];
int parentIndex = (currIndex-1) / 2;
Vertex parentItem = items[parentIndex];
while (currItem.compareTo(parentItem) == -1) {
swap(parentIndex, currIndex);
currIndex = parentIndex;
currItem = items[currIndex];
parentIndex = (currIndex-1) / 2;
parentItem = items[parentIndex];
}
}
public Vertex remove() {
return remove(0);
}
public Vertex remove(Vertex vertex) {
int i = 0;
for (; i < size; i++) {
if (items[i] == vertex) {
break;
}
}
if (i < size) {
return remove(i);
}
return null;
}
private Vertex remove(int index) {
Vertex vertex = items[index];
swap(index, size - 1);
items[size - 1] = null;
size--;
heapifyAfterRemove(index);
return vertex;
}
private void heapifyAfterRemove(int index) {
int currIndex = index;
Vertex currItem = items[currIndex];
int childIndex;
Vertex childItem;
int left = 2 * currIndex + 1;
int right = 2 * currIndex + 2;
if (left > size - 1) {
return;
}
if (right > size - 1) {
childIndex = left;
} else if (items[left].compareTo(items[right]) == -1) {
childIndex = left;
} else {
childIndex = right;
}
childItem = items[childIndex];
while (childItem.compareTo(currItem) == -1) {
swap(currIndex, childIndex);
currIndex = childIndex;
currItem = items[currIndex];
left = 2 * currIndex + 1;
right = 2 * currIndex + 2;
if (left > size - 1) {
return;
}
if (right > size - 1) {
childIndex = left;
} else if (items[left].compareTo(items[right]) == -1) {
childIndex = left;
} else {
childIndex = right;
}
childItem = items[childIndex];
}
}
public boolean isEmpty() {
return size == 0;
}
}
public static class HashMap {
private MapNode[] map;
private char[] keySet;
private int maxSize;
private int size;
public HashMap(int maxSize) {
this.maxSize = maxSize;
map = new MapNode[maxSize];
keySet = new char[maxSize];
}
private static class MapNode {
char key;
int value;
MapNode next;
public MapNode(char key, int value, MapNode next) {
this.key = key;
this.value = value;
this.next = next;
}
}
public int hash(char key) {
return 31 * key;
}
public int getmapIndexOfkey(char key) {
return hash(key) % maxSize;
}
public void put(char key, int value) {
int index = getmapIndexOfkey(key);
map[index] = new MapNode(key, value, map[index]);
keySet[index] = key;
size++;
}
public int get(char key) {
int index = getmapIndexOfkey(key);
MapNode temp = map[index];
while (temp != null) {
if (temp.key == key) {
break;
}
}
if (temp != null) {
return temp.value;
} else {
return -1;
}
}
public char[] keyset() {
return keySet;
}
}
public static class Vertex {
public static final int NEW = 0;
public static final int IN_Q = 1;
public static final int VISITED = 2;
private int state = NEW;
private int cost = Integer.MAX_VALUE;
private char data;
private Neighbour adj;
private int index;
private int parentIndex = -1;
public int compareTo(Vertex other) {
if (cost < other.cost) {
return -1;
}
if (cost > other.cost) {
return 1;
}
return 0;
}
public Vertex(char data, int index) {
this.data = data;
this.index = index;
}
public void addAdjacentVertex(Neighbour adj) {
this.adj = adj;
}
public void updateCost(int newCost, int parentIndex) {
this.cost = newCost;
this.parentIndex = parentIndex;
}
}
public static class Neighbour {
private Neighbour next;
private int index;
private int weight;
public Neighbour(int index, int weight, Neighbour next) {
this.next = next;
this.index = index;
this.weight = weight;
}
}
}
}

QuickSort with Double Linked List

I am having trouble with my swap method in the Quick Sort program. I'm implementing it from a QuickSort method that sorts arrays. Here I take in a file with an integer on each line, it puts the number in a doubly linked list and then sorts the list and outputs to a new file. I need help with the swap method and what else I need to add or do to make it work properly. Any advise would help and examples are best. Thank you
//swap A[pos1] and A[pos2]
public static void swap(DList A, int pos1, int pos2){
int temp = A.get(pos1);
A[pos1] = A[pos2];
A[pos2] = temp;
}
My entire program for quicksort looks like this:
import java.util.*;
import java.io.*;
public class Test_QuickSort{
private static Scanner input = new Scanner(System.in);
private static DList list = new DList();
public static void main(String[] args) throws FileNotFoundException
{
input = new Scanner(new File("data.txt"));
while (input.hasNext())
{
String s = input.nextLine();
DNode g = new DNode(Integer.parseInt(s));
list.addLast(g);
}
//int[] A = {1,4,6,2};
QuickSort(list, 0, list.size()-1);
//for(int i = 0; i < A.length; i++)
// System.out.print(A[i] + " ");
}
public static void QuickSort(DList A, int left, int right){
if(left >= right)
return;
int pivot_index = partition(A, left, right);
QuickSort(A, left, pivot_index - 1);
QuickSort(A, pivot_index + 1, right);
}
public static int partition(DList A, int left, int right){
int pivot = A.get(right);
int index = left;
for(int i = left; i < right; i++){
if(A.get(i) <= pivot){
swap(A, index, i);
index ++;
}
}
swap(A, index, right);
return index;
}
//swap A[pos1] and A[pos2]
public static void swap(DList A, int pos1, int pos2){
int temp = A.get(pos1);
A[pos1] = A[pos2];
A[pos2] = temp;
}
}
My DList Method looks like this:
class DNode {
protected int element; // String element stored by a node
protected DNode next, prev; // Pointers to next and previous nodes
public DNode(int e)
{
element = e;
prev = null;
next = null;
}
public DNode()
{
element = 0;
next = null;
prev = null;
}
public DNode(int e, DNode p, DNode n) {
element = e;
prev = p;
next = n;
}
public int getElement() {
return element; }
public DNode getPrev() {
return prev; }
public DNode getNext() {
return next; }
public void setElement(int newElem) { element = newElem; }
public void setPrev(DNode newPrev) { prev = newPrev; }
public void setNext(DNode newNext) { next = newNext; }
}
public class DList {
protected int size;
protected DNode header, trailer;
public DList() {
size = 0;
header = new DNode(0, null, null);
trailer = new DNode(0, header, null);
header.setNext(trailer);
}
public int size() {
return size; }
public boolean isEmpty() {
return (size == 0); }
public DNode getFirst() throws IllegalStateException {
if (isEmpty()) throw new IllegalStateException("List is empty");
return header.getNext();
}
public DNode getLast() throws IllegalStateException {
if (isEmpty()) throw new IllegalStateException("List is empty");
return trailer.getPrev();
}
public DNode getPrev(DNode v) throws IllegalArgumentException {
if (v == header) throw new IllegalArgumentException
("Cannot move back past the header of the list");
return v.getPrev();
}
public int get(int pos)
{
DNode current = new DNode();
for(int i = 0; i <= pos && current != null; i++)
{
if(pos == 0){
current = header;
}
else{
current = current.next;
break;
}
}
return current.element;
}
public DNode getNext(DNode v) throws IllegalArgumentException {
if (v == trailer) throw new IllegalArgumentException
("Cannot move forward past the trailer of the list");
return v.getNext();
}
public void addBefore(DNode v, DNode z) throws IllegalArgumentException {
DNode u = getPrev(v); // may throw an IllegalArgumentException
z.setPrev(u);
z.setNext(v);
v.setPrev(z);
u.setNext(z);
size++;
}
public void addAfter(DNode v, DNode z) {
DNode w = getNext(v); // may throw an IllegalArgumentException
z.setPrev(v);
z.setNext(w);
w.setPrev(z);
v.setNext(z);
size++;
}
public void addFirst(DNode v) {
addAfter(header, v);
}
public void addLast(DNode v) {
addBefore(trailer, v);
}
public boolean hasPrev(DNode v) {
return v != header; }
public boolean hasNext(DNode v) {
return v != trailer; }
public String toString() {
String s = "[";
DNode v = header.getNext();
while (v != trailer) {
s += v.getElement();
v = v.getNext();
if (v != trailer)
s += ",";
}
s += "]";
return s;
}
}
The reason you are always retrieving the same element in DList.get is that you stop looping after the first iteration. Simply remove the break-statement, and the loop should work as intended.
public int get(int pos)
{
DNode current = new DNode();
for(int i = 0; i <= pos && current != null; i++)
{
if(pos == 0){
current = header;
}
else{
current = current.next;
// break; <-- remove this
}
}
return current.element;
}
Side note: You could get rid of the if-statement, if you would initialize current to header:
public int get(int pos)
{
DNode current = header;
for(int i = 1; i <= pos && current != null; i++)
{
current = current.next;
}
return current.element;
}
Now regarding your swap-method: As already stated, you try to treat the instance of DList as an array by trying to dereference an element using square-brackets. Instead, you should implement a method in DList that allows setting an element at a certain position. For example:
public void setAt(int pos, int value){
DNode current = header;
for(int i = 1; i <= pos && current != null; i++){
current = current.next;
}
if(current != null)
current.setElement(value);
else
throw new IndexOutOfBoundsException();
}
Now you can change your swap-method to:
public static void swap(DList a, int pos1, int pos2){
int temp = a.get(pos1);
a.setAt(pos1, a.get(pos2));
a.setAt(pos2, temp);
}

Iterating through the Circular linked list

I am dealing with the following problem.
I have created a circular list, and i am also able to create x number of nodes for the number of people required in the circle. I am however stuck as i do not know how exactly i will iterate through the list for every nth person(node). I think i will need to create my own iterator but not sure how to go about it. I know it might be possible to import one from library but i don't want to do that as that will kill the learning process for me.
Here is the code for my Node Class
public class Node {
public int iData;
public Node next;
public Node(int x) {
iData = x;
}
public void displayNode() {
System.out.print(iData + " ");
}
}
Here is the code for Circular Linked List
public class CircularList {
private Node first;
private Node last;
private Node current;
private int count; // total items in the list
public CircularList getCurrent;
public CircularList() {
first = null;
last = null;
current = null;
count = 0;
}
public boolean isEmpty() {
return first == null;
}
public void step() {
current = current.next;
}
public Node getCurrent() {
return current;
}
public void insert(int x) {
Node newNode = new Node(x);
if (isEmpty()) {
first = newNode;
current = first;
} else {
current.next = newNode;
}
newNode.next = first;
last = newNode;
step();
count++;
}
public boolean search(int x) {
Node search = first;
int y = 0;
while (search.iData != x && y < count) {
search = search.next;
y++;
}
if (search.iData == x) {
System.out.println("Found the value: " + search.iData);
return true;
} else {
System.out.println("Value not found in list");
return false;
}
}
public void delete(int x) {
Node prev = first;
Node curr = first.next;
int y = 0;
while (y < count && curr.iData != x) {
prev = curr;
curr = curr.next;
}
if (count == 1) {
first = null;
count--;
} else {
prev.next = curr.next;
count--;
}
}
public void displayList() {
int x = 0;
Node printer = first;
while (x < count) {
printer.displayNode();
printer = printer.next;
x++;
}
}
}
Here is the code for my Josephus Class
public class Josephus {
private int numOfPeople; // number of people in a circle
private int countNum; // number used for counting off
CircularList circle;
public Josephus() {
circle = new CircularList();
numOfPeople = 0;
countNum = 0;
}
public void setNumOfPeople(int x) {
numOfPeople = x;
}
public int getNumOfPeople() {
return numOfPeople;
}
public void setCountNum(int x) {
countNum = x;
}
public int getcountNum() {
return countNum;
}
public void addPeople(int x) {
for (int i = 1; i < x; i++) {
circle.insert(i);
}
}
public void display() {
circle.displayList();
}
}
I need guidance in the right direction as to what i should do now. I do not ask for code or the answer. i want someone to push me towards the solutions. I can't go to sleep unless i solve this tonight.

Categories

Resources