QueueAsLinkedList Implementation [closed] - java

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
This is my assignment program in data structure to implement a QueueAsArray. I want someone to guide me about this problem cause I don't have a strong background in java programming.
I'd like someone to give me guidance on what to do to compile and use this code in my main program.
public class QueueAsLinkedList extends AbstractContainer implements Queue
{
protected LinkedList list;
public QueueAsLinkedList ()
{ list = new LinkedList (); }
public void purge ()
{
list.purge ();
count = 0;
}
public Object getHead ()
{
if (count == 0)
throw new ContainerEmptyException ();
return list.getFirst ();
}
public void enqueue (Object object)
{
list.append (object);
++count;
}
public Object dequeue ()
{
if (count == 0)
throw new ContainerEmptyException ();
Object result = list.getFirst ();
list.extract (result);
--count;
return result;
}
public Enumeration getEnumeration()
{
return new Enumeration()
{
protected LinkedList.Element position = list.getHead();
public boolean hasMoreElements()
{
return position != null;
}
public Object nextElement()
{
if (position == null)
throw new NoSuchElementException();
Object result = position.getDatum();
position = position.getNext();
return result;
}
};
}
protected int compareTo (Comparable object)
{
AbstractContainer arg = (AbstractContainer) object;
long diff = (long) getCount() - (long) arg.getCount();
if (diff < 0)
return -1;
else if (diff > 0)
return +1;
else
return 0;
}
public boolean equals(Object object) {
LinkedList list_object = (LinkedList)object;
if(list_object.length != this.length) {
return false;
}
Element ptr = this.head;
Element list_object_ptr = list_object.head;
for(int i = 0; i < this.length; i++) {
if(list_object_ptr.getDatum () != ptr.getDatum ()) {
return false;
}
ptr = ptr.getNext ();
list_object_ptr = list_object_ptr.getNext ();
}
return true;
}
}

My suggestion to you is to read the existing LinkedList libraries source something you can easily find. I suggest you also read the source for ArrayList since you will be wrapping an array. Finally have a look at ArrayBlockingQueue because this is a Queue which wraps an array. This last class is the closest to what you want, but is the most complicated as it is concurrent and thread safe.
When you start writing a class, I suggest you start with something really simple and get that to compile. Using an IDE, it will show you whether the code will compile as you type the code and suggest corrections.
Then I would write a very simple unit test to test your very simple code. You can do this with just one method. (Some people suggest writing the test case first but I find this very hard unless you have written this sort of class before in which case you are not really writing the unit test first, just the first time for that code base)
Then add a second or third method and tests for those.
When it does something you don't understand, use your debugger to step through the code to see what each line does.
I would use an IDE such as Netbeans, Eclipse or IntelliJ CE. I prefer IntelliJ but Netbeans is perhaps the best for a beginner.
Download the IDE.
start a new project.
create a class and copy and paste the code into that class.
create another class which uses that class. This is your class.
BTW Did you write the class or was it given to you because it has more than a few unusual coding choices.
Comments on the code
Its a Queue which wraps a class which implements a Queue so delegation appears natural, but it doesn't appear to do this suggesting that LinkedList and Queue are not the standard LinkedList and Queue which is confusing.
it uses a field count which is not defined instead of the LinkedList.size().
dequeue accesses the LinkedList twice when once would be more efficient (as the standard library does)
It supports Enumeration instead of Iterator when Iterator was been the standard since Java 1.2 (1998)
compareTo is 0 when equals is false which is a bug.
it doen'ts support generics which the builtin one does.
compareTo only examines length so a queue with "A" and a queue with "Z" are compareTo == 0
equals uses this.head and this.length which are not fields.

Related

How to use Comparable as a Generic parameter in a Class

I have a home work in a data structures course, the question is:
Implementation of doubly-linked list class.
the methods:
display()
length() or size()
insertSorted(Comparable)
insertToEnd(Comparable)
insertToHead(Comparable)
delete(Comparable)
boolean search(Comparable)
You must do this in JAVA
Create an application layer to test your class and its methods.
Compress all of your source files into a file and rename it as CS214HW1_first_lastName.zip Put your name in the filename. If needed, add a ReadMe.txt file for extra information such as compilation.
I implemented everything correctly and the code is working fine, but I used for example: insertSorted(int) instead of insertSorted(Comparable), because I didn't know how to do it.
I searched online, and read the JAVA documentation for (Comparable) but it is not enough :(
Can anybody help, please it is very important?
Here's some of my code, I can't write it all, cuz I don't want my friends to get the same code.
I will take zero if there is same code.
Code:
class DLL {
class Node {
Node next;
Node prev;
int data;
Node() {
next = null;
prev = null;
data = 0;
}
Node(int dt) {
next = null;
prev = null;
data = dt;
}
}
Node head;
void insertToHead(int dt) {
if (head == null) {
head = new Node(dt);
}
else {
head.prev = new Node(dt);
head.prev.next = head;
head = head.prev;
}
}
public static void main(String args[]) {
DLL dll = new DLL();
dll.insertToHead(1);
dll.insertToHead(2);
dll.insertToHead(3);
}
}
Please, somebody, tell me what to change in the beginning of the class.
are we gone use extends or implements Comparable<E> or what!
and what changes should i do the method insertToHead(Comparable)
what changes should i do to the main.
You would probably like to look into how generics work as well. The basic idea is that you would like to set up your class so that it will not know exactly the specific type of object but can be given some hint at the types of things it can expect of a declared generic type.
In your case, you would like to set up your list so that you can create linked lists of anything that can be compared. Java has a class for that which you have mention called Comparable<E> this tells Java that it will be able to call such methods as compareTo on the provided object.
More specifically to your closing questions:
Use the following style of class declaration MyClass<MyGenericType extends Comparable<MyGenericType>>. In your case DLL<E extends Comparable<E>>.
Switch the method arguments to accept E our declared generic type.
You should use the class Integer instead of the primitive type int, and change the creation of your list to DLL<Integer> dll = new DLL<Integer>().
Fully updated version of provided code:
public class DLL<E extends Comparable<E>> {
class Node {
Node next;
Node prev;
E data;
Node() {
next = null;
prev = null;
data = null;
}
Node(E dt) {
next = null;
prev = null;
data = dt;
}
}
Node head;
void insertToHead(E dt) {
if (head == null) {
head = new Node(dt);
}
else {
head.prev = new Node(dt);
head.prev.next = head;
head = head.prev;
}
}
public static void main(String args[]) {
DLL<Integer> dll = new DLL<Integer>();
dll.insertToHead(1);
dll.insertToHead(2);
dll.insertToHead(3);
}
}
This new implementation should provide a hint for how to proceed with some of the other homework tasks. For instance you can now compare objects just by their compareTo method which might useful for sorting hint hint.
That doc page gives a very good explanation for how to use this method. You should note that in their docs, they use a generic type called T instead of E, it really doesnt make a difference you can call it whatever you want provided it is unique to your program.
Edit:
An each hint in the sorting direction:
Ojbects which extend the Comparable class have a method which is called compareTo this method is set up so you can call:
object1.compareTo(object2);
this method returns an int which will be:
> 0 when object1 is greater than object2
= 0 when object1 is equal to object2
< 0 when object1 is less than object2
I don't want to give away too much as this is a homework assignment but here is my hint:
The way the above code sets up your classes, you would be able to tell the relationship between NodeA and NodeB by calling:
NodeA.data.compareTo(NodeB.data)
this will return an integer which gives your information according to the list above.
The <=,>=,== operators are likely found in the Integer class's compareTo method.
Something like:
public int compareTo(Object o) {
int otherNumber = ((Integer) o).intValue();
int thisNumber = this.intValue();
if (otherNumber > thisNumber) {
return 1;
} else if (otherNumber < thisNumber) {
return -1;
} else {
return 0;
}
}
but more likely they just do something like:
public int compareTo(Object o) {
return this.intValue() - o.intValue(); // possibly normalized to 1, -1, 0
}
See the Docs on Integer for more info on this.

Is there any way I can return a value from a loop and continue from where I left off?

Is there any way I can return a value from a loop and continuing from where I left off ?
In the following snippet, I want to return the current value of currVm. But I am unable to do so.
In the innermost loop of the snippet :
while(c <= currVm) {
allocatedVm(currVm);
c++;
}
a function named allocatedVm is called. I want to return the value of currVm and start again from where I left off. Is there any way out ?
#Override
public int getNextAvailableVm() {
Set<String> dataCenters = confMap.keySet();
for (String dataCenter : dataCenters) {
LinkedList<DepConfAttr> list = confMap.get(dataCenter);
Collections.sort(list, new MemoryComparator());
int size = list.size() - 1;
int count = 0;
while(size >= 0) {
DepConfAttr dca = (DepConfAttr)list.get(count);
int currVm = dca.getVmCount();
int c = 0;
while(c <= currVm) {
allocatedVm(currVm); // RETURN currVm
c++;
}
count++;
size--;
}
}
}
The best approach would probably be to write a method returning an Iterable<Integer>. That's not as easy in Java as it is in languages which support generator functions (e.g. C# and Python) but it's still feasible. If the code is short, you can get away with a pair of (nested) anonymous inner classes:
public Iterable<Integer> foo() {
return new Iterable<Integer>() {
#Override public Iterator<Integer> iterator() {
return new Iterator<Integer>() {
// Implement hasNext, next and remove here
};
}
};
}
In your case I'd be tempted to break it into a separate non-anonymous class though, just for simplicity.
Anyway, the point of using Iterable is that an Iterator naturally has state - that's its purpose, basically. So it's a good fit for your requirements.
Another rather simpler approach would be to return all of the elements in one go, and make the caller perform the allocation on demand. Obviously that doesn't work well if there could be a huge number of elements, but it would be easier to understand.
not sure i understand what you need, but:
if you wish to notify the caller of the method that you've got a value during the running of the method, but don't wish to exit the method just yet, you can use listeners.
just create an interface as a parameter to your function, and have a function inside that will have the object as a parameter.
example:
interface IGotValueListener
{
public void onGotValue(MyClass obj);
}
public int getNextAvailableVm(IGotValueListener listener)
{
...
if(listener!=null)
listener.onGotValue(...);
}
now , for calling the method, you do:
int finalResult=getNextAvailableVm(new IGotValueListener ()
{
... //implement onGotValue
};
You can return from anywhere in your method , by just putting the return keyword. If you want to put a functionality to resume ur method from different places then u need to factor ur method in that way. You can use labels and if statements, set some static variables to mark the last execution place. If your application is not multi-threaded then u need not to worry with the use of static variable synchronization. Also if your method is too big and becoming hard to follow/read, then think about breaking it into smaller ones.

Java: Implement stack with one queue, any problems?

So I tried to implement a stack with just one queue and it appears to work, but I'm not sure if there's something wrong with it since most of the solutions I've seen online use two queues. Can anyone tell if me if there are problems with my implementation?
public class MyStack<T> {
/**
* #param args
*/
private Queue<T> q = new LinkedList<T>();
public MyStack(){
}
public static void main(String[] args) {
// TODO Auto-generated method stub
MyStack<String> s = new MyStack<String>();
s.push("1");
s.push("2");
s.push("3");
s.push("4");
System.out.println(s.pop());
System.out.println(s.pop());
System.out.println(s.pop());
System.out.println(s.pop());
System.out.println(s.pop());
}
public void push(T s){
q.offer(s);
}
public T pop(){
int n = q.size();
for(int i = 0; i < n-1; i++){
q.offer(q.poll());
}
return q.poll();
}
}
Output:
4
3
2
1
null
Your solution is inefficient because you have to loop through the whole stack every time you pop something from it. (Effectively you have to traverse the whole linked list, before removing the element that was at the end.)
Edit: Java's linked list is doubly linked anyway, so this is entirely pointless.
You should use either a Stack or a Deque or even a LinkedList.
Implementing your own is just ... pointless. Unless of course (as #bas suggests) you are doing a course on data structures in which case you should go Commando and implement your own structure from scratch. Using another structure because it is nearly like the one you are trying to make is like using a hammer with screws.
If you really need to implement something yourself something like this should work:
public class Stack<T> {
private Entry top = null;
private class Entry {
final Entry up;
final T it;
public Entry(Entry up, T it) {
this.up = up;
this.it = it;
}
}
public void push ( T it ) {
top = new Entry(top, it);
}
public T pop () {
if ( top == null ) {
throw new EmptyStackException();
}
T it = top.it;
top = top.up;
return it;
}
}
NB: This may not be thread safe.
There is absolutely no reason a stack should use two queues. As a matter of fact, it only needs to keep track of one top-node that references the nodes below it.
The code seems to work, but as nachokk said, this is not the site for code review. This site is ment if you run into errors and require assistance.
You must use two queues ONLY when you have basic queues operations, like enqueue and dequeue. When you can use other methods, especially iterating over queue, you can do it with only one queue, like you did.

How to use a method from a generic object list iterator to call another class' equals method

I am taking an intro to Java course, and we are learning about how to make a generic object list iterator (I call it List) that can be extended into more specific lists later. This way, if I decide to make another list class later on, I can just extend List instead of going through typing all the getters, setters, insert(), delete(), etc. again.
My professor wants our List class to have an isThere() method. She wants it to accept an object, iterate through the list until it finds a match, and then return the index of where it found it. I have searched for similar questions on this site, but most of the methods suggested include "<>", or hash which we are not allowed to use in this class. We are also not allowed to use any Array method that java provides for us. We must write our own methods.
So, my problem is that I have stored 10 Users in my Object List. I intentionally stored one element as "Bimmy" so that I could try to find that element using my isThere() method. When I went through debug mode, it shows that it reaches the User method equals() and then returns false. Debug also shows that the User's names are both "Bimmy" and the id values are also the same (Users having the same name and id are the requirements for the equals method to return true).
Again, this is my first semester taking Java, and I think my problem has to do with casting. I think that in the List's isThere(), "list[i]" doesn't know that it is a User, or that it should compare itself to the other User object. However, I am really not sure. If anyone would be so kind as to help, I would greatly appreciate it. I will post the code below...
List isThere() method:
public int isThere(Object obj)
{
for(int i = 0; i<index; i++)
{
if(list[i].equals(obj))
{
return i;
}
}
return -1;
}
The User's equal() method:
public boolean equals(User user)
{
if(user.getName().equals(name) && user.getId().equals(id))
{
return true;
}
else
return false;
}
This is what I am doing in Main:
System.out.println("-----------------------------test isThere()");
UserList check = new UserList(10);
check.tryAdd(new User("Jimmy", "562801"));//I am adding 10 Users here.
check.tryAdd(new User("Jimmy", "562801"));//I put one as "Bimmy" so that I can
check.tryAdd(new User("Jimmy", "562801"));//test this method to find that User
check.tryAdd(new User("Jimmy", "562801"));//at index 8
check.tryAdd(new User("Jimmy", "562801"));
check.tryAdd(new User("Jimmy", "562801"));
check.tryAdd(new User("Jimmy", "562801"));
check.tryAdd(new User("Jimmy", "562801"));
check.tryAdd(new User("Bimmy", "562801"));
check.tryAdd(new User("Jimmy", "562801"));
System.out.println(check.toString());
System.out.println(check.isThere( new User("Bimmy","562801")));
At this point the console outputs -1 meaning "Bimmy" was not found. I am not sure how to fix this problem, but I am looking forward to learning what I have done wrong.
This is more about my list:
protected final int MAXSIZE=10;
protected Object [] list;
protected int index;
protected int curPos;
public List()
{
list = new Object[MAXSIZE];
for(int i = 0;i<MAXSIZE; i++)
{
list[i]=new Object();
}
index = 0;
curPos = 0;
}
public List(int size)
{
list = new Object[size];
for(int i = 0;i<size; i++)
{
list[i]=new Object();
}
index = 0;
curPos = 0;
}
adding elements
public void tryAdd(Object thing)//adds Object to index, increment index. if full, it deques first
{
if(isFull())
{
deque();
setElement(thing,index-1);
}
else
{
setElement(thing,index);
index++;
}
}
public void setElement(Object setWhat, int which) //assigns a specific element with the parameters
{
list[which] = setWhat;
}
Also UserList:
public UserList(int size){super(size);}
I believe it's calling the Object.equals method (which actually just checks if they're the exact same object) (every object is a subclass of Object).
This is because you're calling
list[i].equals(obj)
where obj is of type Object (even though it's actual type is User).
Having your equals method override Object.equals should work:
#Override
public boolean equals(Object other)
{
User user = (User)other;
if(user.getName().equals(name) && user.getId().equals(id))
return true;
else
return false;
}
An alternative that should work is changing the type of the input parameter of isThere to User.

how do i make a stack out of a linked list? [duplicate]

This question already has answers here:
Closed 10 years ago.
I'm trying to create a Stack to take a string and add each of the strings characters to it, but I was told it would be far more efficient use a LinkedList. How would I use a LinkedList to create and manipulate a stack?
An example would be very appreciated!
Ok, the problem is that you're not using First at all. Try the following:
public class Example
{
private LinkedList aList = new LinkedList();
public void push(char c) {
aList.addFirst(c);
}
public Object pop() {
return aList.removeFirst();
}
public boolean empty() {
return aList.isEmpty();
}
public static void main(String[] args) {
Stack exmpStack = new Stack();
String ranString = "Dad";
for (int i = 0; i < ranString.length(); i++) {
exmpStack.push(ranString.charAt(i));
}
while (!exmpStack.empty()) {
System.out.print(exmpStack.pop());
}
}
}
Because you never use First it's always null - so your loop never runs at all! Instead of using that at all, just use the build in isEmpty() function.
Edit: Of course, you don't really need those functions at all - the following will work fine:
public class Example
{
private LinkedList aList = new LinkedList();
public static void main(String[] args) {
String ranString = "Dad";
for (int i = 0; i < ranString.length(); i++) {
aList.push(ranString.charAt(i));
}
while (!aList.isEmpty()) {
System.out.print(aList.pop());
}
}
}
Now this is still a bit unsafe - you can go one step further by using the following:
private LinkedList<Character> aList = new LinkedList<>();
That way it's a bit safer, and returns Characters instead of Objects - and Characters can be implicitly cast to char :)
Java's LinkedList is a doubly linked list, with efficient accessors to get, add, and remove elements both at the end and at the head of the list, so you can use those methods to emulate a stack.
A LinkedList provides more operations that that of a stack.
You use a stack for pushing and popping your characters of your string. However you can only retrieve the character in the order that opposite the way you insert your string. So are you sure if you want this behaviour.
A linkedlist allows you to add/retrieve your data either from head / tail.
LinkedList is indeed more efficient, as Stack comes with synchronized methods by virtue of its reliance on Vector. In single-threaded applications, using the latter means paying the synchronization price for no benefit. Even in multi-threaded applications, you may want more control over synchronization.
Here's a possible LinkedList based solution. Please note the use of composition instead of inheritance. This will give you a well behaved Stack that cannot be abused by using List-related methods.
class MyStack<T> {
private List<T> list = new LinkedList<T>();
public void push(T object) { list.add(0, object); }
public T pop(T object) {
if (isEmpty()) throw new NoSuchElementException();
return list.remove(0);
}
public boolean isEmpty() { return list.isEmpty(); }
}
Nonetheless, if your stack is meant only for string characters as your question suggests, you might want to emulate a stack directly on a dynamic character array. I will leave that as an exercise to the reader, or I may provide it in a future edit.
Here is the sample: Stack implementation. Hope it helps.
It is done with C# but you get the idea

Categories

Resources