Implementing own hashset - java

I was studying about hashset in java and for that I am writing creating my own hashset which will double its size everytimme the threshold value is reached..here I am keeping the threshold as 0.75 of original size . However my code is running into an infinite loop. I tried debugging it but was not able to find my error...
here is the code
package drafta;
import java.util.Iterator;
import java.util.NoSuchElementException;
public class HashSet
{
private Node[] buckets;
private int currentSize;
private int current;
public HashSet(int bucketsLength)
{
buckets=new Node[bucketsLength];
currentSize=0;
}
public boolean contains(Object x)
{
return false;
// don't implement for the draft
}
public boolean add(Object x)
{
int key=gethashcode(x);
Node node = buckets[key];
while(node!=null){
if(node.data.equals(x)){
return false;
}
}
if(buckets[current]==null){
node = new Node(x);
current=key;
buckets[key]=node;
currentSize++;
}else{
node = new Node(x);
node.next=buckets[current];
current=key;
buckets[key]=node;
currentSize++;
}
System.out.println("add successful "+ x);
System.out.println(" size "+currentSize+" rehash "+buckets.length*0.75);
if(currentSize>(buckets.length*0.75)){
rehash();
}
return true;
}
private void rehash() {
Node temp=buckets[current];
Object s[]=new Object[buckets.length];
buckets=new Node[2*buckets.length];
currentSize=0;
int i=0;
while(temp!=null){
s[i]=temp.data;
temp=temp.next;
i++;
}
while(i>0){
add(s[--i]);
}
}
public boolean remove(Object x)
{
return false;
// don't implement for draft
}
public int gethashcode(Object x){
int hc = x.hashCode();
if(hc<0)
hc=-hc;
return (hc%buckets.length);
}
public Iterator<Object> iterator()
{
Iterator <Object> i=new HashSetIterator();
return i;
//
}
public int size()
{
return currentSize;
//
}
private void resize(int newLength)
{
}
public int getlength()
{
return buckets.length;
//
}
class Node
{
public Object data;
public Node next;
public Node(Object x) {
data=x;
}
public String toString(){
return data.toString();
}
}
class HashSetIterator implements Iterator<Object>
{
private int bucket=0;
private Node currentnode;
public HashSetIterator()
{
currentnode=buckets[current];
}
public boolean hasNext()
{
if(currentnode.next!=null)
return true;
else
return false;
//
}
public Object next()
{
return currentnode.next;
//
}
#Override
public void remove() {
currentnode.next=currentnode.next.next;
}
}
}
this is the main class which I am using to test my code
package drafta;
import java.util.Iterator;
public class HashSetTester
{
public static void main(String[] args)
{
HashSet names = new HashSet(5);
names.add("Harry");
names.add("Sue");
names.add("Nina");
System.out.println(names.size() + " " + names.getlength());
names.add("Susannah");
System.out.println(names.size() + " " + names.getlength());
System.out.println();
names.add("Larry");
names.add("Juliet");
names.add("Katherine");
names.add("Romeo");
names.add("Maria");
System.out.println(names.size() + " " + names.getlength());
names.add("Ann");
names.add("Taylor");
System.out.println(names.size() + " " + names.getlength());
}
}
can someone please point out my mistake..the code is going into infintie loop when it calls rehash for second time..first time it goes through correctly...

You arn't changing any conditions in your while loop in the add method - so there is no reason for it to break out.
while(node!=null){
if(node.data.equals(x)){
return false;
}
}
You will continue looping until the node is null (which never gets set) or the node data ever equals x, but the data value also never gets set.

Related

How i can do search() with stack

I'm trying to figure out how i can show all numbers in the stack i have, to do search method without using library. For example
if(value = allNumbers){
return true;
}
else{
return false;
}
The problem is I can't find the correct method how to display allNumbers in the stack
My code:
public class Stack <T>{
private Item<T> q=null;
public boolean isEmpty() {
return q==null;
}
public void push(T d) {
Item<T> tmp=new Item<T>(d);
tmp.next=q;
q=tmp;
}
public T pop() {
if (isEmpty())
return null;
T tmp=q.data;
q=q.next;
return tmp;
}
public T peek(){
if (isEmpty())
return null;
T tmp = q.data;
return tmp;
}
// public boolean search (T value) {
// if(value == null ) {
// return false;
// }
// else{
// value = allNumbers ;
// return true;
// }
//
// }
}
Driver code:
public class Driver {
public static void main(String[] args) {
Stack<Integer> s=new Stack<Integer>();
int value = 2;
s.push(1);
s.push(2);
s.push(3);
s.push(4);
s.push(5);
s.push(6);
s.push(7);
s.push(8);
s.push(9);
System.out.println("Popped: " + s.pop());
System.out.println("Last number put in is: " + s.peek());
// System.out.println("Searching for: " );
// System.out.println("Is found: " + s.search(9));
while (!s.isEmpty()) {
System.out.println(s.pop());
}
}
}
I would assume your 'Item' class is custom since you haven't added any imports. The solution with that in mind is to add a method that takes in one parameter (data) and traverses all the items in the "q" list. If an item matches the data, return true. If not, return false. Also, remember to implement the 'equals()' method appropriately in the 'Item' class.
The implementation of the search method should be pretty much this:
public boolean search(T value) {
if (value == null) {
return false;
}
Item<T> item = q;
while (q != null) {
if (q.equals(value))
return true;
}
return false;
}

What is wrong with this code? It won't run

public class StackSimple{
private long capacity=1000;//maximum size of array
private int idx_top;
private Object data[];
public StackSimple(int capacity)
{
idx_top=-1;
this.capacity=capacity;
data = new Object[capacity];
}
public boolean isEmpty(){
return(idx_top<0);
}
public boolean isFull(){
return(idx_top>=capacity-1);
}
public int size()
{
return idx_top+1;
}
public boolean push(Object x){
if (isFull()){
throw new IllegalArgumentException("ERROR:Stack Overflow.Full Stack");
}
else
{`enter code here`data[++idx_top]=x;
return true;
}
}
public Object pop(){
if(isEmpty())
throw new IllegalArgumentException("ERROR:Stack Underflow.Empty Stack.");
else{
return data[idx_top--];
}
}
public Object top(){
if (isEmpty())
throw new IllegalArgumentException("ERROR:Stack Underflow.Empty Stack.");
else{
return data[idx_top];
}
}
public void print()
{`
for (int i=size()-1;i>=0;i--)
System.out.println(data[i]);
}
}
public class Stack_Exercise {
public static void main(String[] args) {
StackSimple s = new StackSimple(capacity:3);//error shows here
s.push(x:"books");`enter code here`
s.push(x:"something");
s.push(x:"200");
s.print();
System.out.println("Size=" +s.size());
}
}
Why doesn't this work?
Why does it say invalid statement while creating the StackSimple object? The problem is in the main class while running it. There are errors while pushing the elements.
Error while compiling
When passing parameters to a function you just pass the values.
In your case not StackSimple(capacity:3) but just StackSimple(3)
First question, which version of Java are you using.
Second, in Java you should be passing as a variable instead of StackSimple(capacity:3). Change your main method to below, here is my recommendation:
StackSimple s = new StackSimple(3);
s.push("books");
s.push("something");
s.push("200");
s.print();
System.out.println("Size=" +s.size());
You are not at all pushing the value in the stack, your pusch function is not working as it is expected to work.
Here is the correct program.
class StackSimple {
private long capacity = 1000;// maximum size of array
private int idx_top;
private Object data[];
public StackSimple(int capacity) {
idx_top = -1;
this.capacity = capacity;
data = new Object[capacity];
}
public boolean isEmpty() {
return (idx_top < 0);
}
public boolean isFull() {
return (idx_top >= capacity - 1);
}
public int size() {
return idx_top + 1;
}
public boolean push(Object x) {
if (isFull()) {
throw new IllegalArgumentException("ERROR:Stack Overflow.Full Stack");
} else {
data[++idx_top] = x;
return true;
}
}
public Object pop() {
if (isEmpty())
throw new IllegalArgumentException("ERROR:Stack Underflow.Empty Stack.");
else {
return data[idx_top--];
}
}
public Object top() {
if (isEmpty())
throw new IllegalArgumentException("ERROR:Stack Underflow.Empty Stack.");
else {
return data[idx_top];
}
}
public void print() {
for (int i = size() - 1; i >= 0; i--)
System.out.println(data[i]);
}
}
public class test {
public static void main(String[] args) {
StackSimple s = new StackSimple(3);// error shows here
s.push("books");
s.push("something");
s.push("200");
s.print();
System.out.println("Size=" + s.size());
}
}

Properly Writing Object Oriented Code in java for a stack

I'm trying to write code in a way that it is object oriented. In this particular case I want to keep track of the minimum value of my stack in O(1) time. I know how to do it, the idea of it, well my idea of it, which is to have another stack that keeps track of the minimum value for every push and pop.
I've nested every class inside of the program class which is called minStack, which doesn't seem like the right thing to do however when I create a instance of minStack and call its variables it works out fine for a regular stack. I created a class that extends a Stack called StackWithMin but I don't know how to call its values. Should I create a new instance of a StackWithMin? If so how would i do it? I did it at the end of the code above the main function, but peek() always returns null
class minStack {
public class Stack {
Node top;
Object min = null;
Object pop() {
if(top != null) {
Object item = top.getData();
top = top.getNext();
return item;
}
return null;
}
void push(Object item) {
if(min == null) {
min = item;
}
if((int)item < (int)min) {
min = item;
}
Node pushed = new Node(item, top);
top = pushed;
}
Object peek() {
if(top == null) {
//System.out.println("Its null or stack is empty");
return null;
}
return top.getData();
}
Object minimumValue() {
if(min == null) {
return null;
}
return (int)min;
}
}
public class Node {
Object data;
Node next;
public Node(Object data) {
this.data = data;
this.next = null;
}
public Node(Object data, Node next) {
this.data = data;
this.next = next;
}
public void setNext(Node n) {
next = n;
}
public Node getNext() {
return next;
}
public void setData(Object d) {
data = d;
}
public Object getData() {
return data;
}
}
public class StackWithMin extends Stack {
Stack s2;
public StackWithMin() {
s2 = new Stack();
}
public void push(Object value) {
if((int)value <= (int)min()) {
s2.push(value);
}
super.push(value);
}
public Object pop() {
Object value = super.pop();
if((int)value == (int)min()) {
s2.pop();
}
return value;
}
public Object min() {
if(s2.top == null) {
return null;
}
else {
return s2.peek();
}
}
}
Stack testStack = new Stack();
StackWithMin stackMin = new StackWithMin();
public static void main(String[] args) {
minStack mStack = new minStack();
//StackWithMin stackMin = new StackWithMin();
mStack.testStack.push(3);
mStack.testStack.push(5);
mStack.testStack.push(2);
mStack.stackMin.push(2);
mStack.stackMin.push(4);
mStack.stackMin.push(1);
System.out.println(mStack.testStack.peek());
System.out.println(mStack.stackMin.peek());
mStack.testStack.pop();
}
}
I would suggest to create generic interface Stack like this one
interface Stack<T> {
void push(T item);
T pop();
T peek();
}
Generics add stability to your code by making more of your bugs
detectable at compile time.
See more about generics here.
Then implement this interface in a common way. All implementation details will be hidden inside of this class (your Node class for example). Here is the code (it is just to show the idea, if you want to use it you need to improve it with exception handling for example). Note that class Node is now also generic.
class SimpleStack<T> implements Stack<T> {
private class Node<T> { ... }
private Node<T> root = null;
public void push(T item) {
if (root == null) {
root = new Node<T>(item);
} else {
Node<T> node = new Node<T>(item, root);
root = node;
}
}
public T pop() {
if (root != null) {
T data = root.getData();
root = root.getNext();
return data;
} else {
return null;
}
}
public T peek() {
if (root != null) {
return root.getData();
} else {
return null;
}
}
}
Now we get to the part with stored minimum value. We can extend our SimpleStack class and add field with another SimpleStack. However I think this is better to make another implementation of the Stack and store two stacks for values and for minimums. The example is below. I have generalize the class that now uses Comparator to compare object, so you can use any other object types.
class StackWithComparator<T> implements Stack<T> {
private Comparator<T> comparator;
private SimpleStack<T> mins = new SimpleStack<>();
private SimpleStack<T> data = new SimpleStack<>();
public StackWithComparator(Comparator<T> comparator) {
this.comparator = comparator;
}
public void push(T item) {
data.push(item);
if (mins.peek() == null || comparator.compare(mins.peek(), item) >= 0) {
mins.push(item);
} else {
mins.push(mins.peek());
}
}
public T pop() {
mins.pop();
return data.pop();
}
public T peek() {
return data.peek();
}
public T min() {
return mins.peek();
}
}
Now you can use both implementations like so
SimpleStack<Integer> s1 = new SimpleStack<>();
s1.push(1);
s1.push(2);
s1.push(3);
System.out.println(s1.pop()); // print 3
System.out.println(s1.pop()); // print 2
System.out.println(s1.pop()); // print 1
StackWithComparator<Integer> s2 = new StackWithComparator<>(new Comparator<Integer>() {
public int compare(Integer o1, Integer o2) {
return Integer.compare(o1, o2);
}
});
s2.push(1);
s2.push(2);
s2.push(3);
s2.push(0);
s2.push(4);
System.out.println(s2.min() + " " + s2.pop()); // print 0 4
System.out.println(s2.min() + " " + s2.pop()); // print 0 0
System.out.println(s2.min() + " " + s2.pop()); // print 1 3
System.out.println(s2.min() + " " + s2.pop()); // print 1 2
System.out.println(s2.min() + " " + s2.pop()); // print 1 1

Creating queue from two stacks

Can someone explain what am I doing wrong here ?
I am trying to create a queue from two stacks as per a book exercise. I get error "Stack Underflow" from the peek function. But everything seems right to me :P Please explain. Thanks!
//Program to implement Queue using two Stacks.
import java.util.NoSuchElementException;
public class Ex3_5_Stack {
int N;
int countOfNodes=0;
private Node first;
class Node {
private int item;
private Node next;
}
public Ex3_5_Stack() {
first=null;
N=0;
}
public int size() {
return N;
}
public boolean isEmpty() {
return first==null;
}
public void push(int item){
if (this.countOfNodes>=3) {
Ex3_5_Stack stack = new Ex3_5_Stack();
stack.first.item=item;
N++;
} else {
Node oldfirst = first;
first = new Node();
first.item=item;
first.next=oldfirst;
N++;
}
}
public int pop() {
if (this.isEmpty())
throw new NoSuchElementException("Stack Underflow");
int item = first.item;
first=first.next;
return item;
}
public int peek() {
if (this.isEmpty())
throw new NoSuchElementException("Stack Underflow");
return first.item;
}
}
And MyQueue file
public class Ex3_5_MyQueue {
Ex3_5_Stack StackNewest,StackOldest;
public Ex3_5_MyQueue() {
super();
StackNewest = new Ex3_5_Stack();
StackOldest = new Ex3_5_Stack();
}
public int size() {
return StackNewest.size()+StackOldest.size();
}
public void add(int value) {
StackNewest.push(value);
}
private void transferStack() {
if (StackOldest.isEmpty()) {
while (StackNewest.isEmpty()) {
StackOldest.push(StackNewest.pop());
}
}
}
public int peek() {
this.transferStack();
return StackOldest.peek();
}
public int remove() {
this.transferStack();
return StackOldest.pop();
}
public static void main(String[] args) {
Ex3_5_MyQueue myQueue = new Ex3_5_MyQueue();
myQueue.add(4);
myQueue.add(3);
myQueue.add(5);
myQueue.add(1);
System.out.println(myQueue.peek());
}
}
In transferStack(), you're missing an exclamation mark. It should be:
private void transferStack(){
if(StackOldest.isEmpty()){
while(!StackNewest.isEmpty()){ // you forgot it here
StackOldest.push(StackNewest.pop());
}
}
}

Showing contents of a LinkedStack without removing them

I am a beginner in java and I am currently working Nodes. I was wondering if there was a way to show the content of a list without having to use .getNext method, because once I use it, it removes the element that was on the Node well literally removes the Node on top. What I am trying to do in this code is using input to store two String elements in the new two Nodes then using the method proveTitle to prove that those elements are on the list. Once I do that I make sure that elements are still intact and use the toString method to check the list. Note that in the class of Book for some strange reason the
T isnt showing besides the class and the implemented class if I put the <> around it.
Heres the code:
myNode class:
public class myNode<T>
{
private T data;
private myNode next;
public myNode(T _data)
{
data = _data;
}
public myNode(T _data, myNode _next)
{
data = _data;
next = _next;
}
public T getData()
{
return data;
}
public void setData(T _data)
{
data = _data;
}
public myNode getNext()
{
return next;
}
public void setNext(myNode _next)
{
next = _next;
}
}
Interface class:
public interface myInterface<T>
{
public void pushTitle(T data);
public T pop();
public T peek();
public String toString();
public boolean isEmpty();
public int size();
public myNode getNode();
}
Book class, which contains the methods
public class Book implements myInterface
{
private int count;
private T author;
private T title;
private int stock;
private myNode<T> top;
public Book()
{
count = 0;
top = null;
}
#Override
public myNode getNode()
{
return top;
}
#Override
public void pushTitle(T title)
{
myNode<T> current = new myNode<>(title, top);
current.setNext(top);
top = current;
count++;
}
public void proveTitle(T title)
{
T result;
myNode<T> current = top;
if(title.equals(current.getData()))
{
result = current.getData();
System.out.println("The title " + "'" + result + "'" + " exist.");
top = top.getNext();
}
}
#Override
public T pop()
{
T result;
if(count == 0 || top == null )
{
System.out.println("List is empty");
}
System.out.println("The element on top is:" + top.getData());
result = top.getData();
top = top.getNext();
count--;
return result;
}
#Override
public T peek()
{
System.out.println("Element on top is: " + top.getData());
return top.getData();
}
#Override
public boolean isEmpty()
{
if(top == null)
{
System.out.println("The list is empty");
}
else
{
System.out.println("The list is not empty." + "It has" + count + "elements");
}
return top == null;
}
#Override
public int size()
{
System.out.println("The size of the list is" + count);
return count;
}
#Override
public String toString()
{
String result = "";
myNode current = top;
System.out.println("Top");
while(current != null)
{
result += ("[" + current.getData() + "]\n");
current = current.getNext();
}
return result + "Bottom";
}
}
main class:
package node;
import java.util.Scanner;
public class myDriver
{
public static void main(String[]args)
{
Scanner input = new Scanner(System.in);
Book<String> title = new Book<>();
myNode<String> current;
current = title.getNode();
String push;
String push2;
System.out.println("Enter title of book 1");
push = input.nextLine();
title.pushTitle(push);
System.out.println("Enter title of book 2");
push2 = input.nextLine();
title.pushTitle(push2);
title.proveTitle(push);
title.proveTitle(push2);
System.out.println(title.toString());
}
}
Output:
run:
Enter title of book 1
Tiger
Enter title of book 2
crossed
The title 'crossed' exist.
Top
[Tiger]
Bottom
BUILD SUCCESSFUL (total time: 7 seconds)
You seem to be trying to implement a List using a Stack. These are very different data structures. What you are trying to do is very easy in a List. In a Stack it requires that you have a second stack. As you pop each object off the current stack, you push it onto the second stack.
If order doesn't matter, you can do this once and switch to using the second stack. If order does matter, you will have to reverse the process to get back your original stack.
Also note that the better approach would probably be to just use a List.

Categories