Java implementing Queue by extending LinkedList - java

I've been trying to research a way to implement a Queue using a LinkedList. I've mostly found examples showing me how to do it by literally using "implements" in the class. BUT What I'd like to do, however, is to extend the LinkedList class. For example I have written something like this:
public class TestQueue extends LinkedList{
public TestQueue(){
}
public void enqueue(ObjectType c){
add(c);
}
public Object dequeue(){
return (ObjectType ) remove();
}
// more code for peek and size ect....
}
Is this really all I have to do to use a linked-list type queue? How then would I have to set a head(front) and a tail(rear) to use the linked list just like a queue?
Thanks in advance.

From my understanding and looking up the LinkedList class, you should be good to go as the only thing you should need is the Queue class, which LinkedList already includes. I would recommend taking a quick look at these resources however just to make sure your understanding is where you want it to be.
API from Oracle - http://docs.oracle.com/javase/7/docs/api/java/util/LinkedList.html
Learning about Queues & Staks (Document) - http://introcs.cs.princeton.edu/java/43stack/

Related

How to change the node in the built-in java LinkedList class to add a right and down pointer?

I have started to use Java. I want to use the built-in Java LinkedList class with my custom node class (my node class will contain fields: data, down pointer, right pointer). Is it possible to do so?
Here is my node class:
public class Node {
int data;
Node rt;
Node dw;
//constructor
public Node(int dataValue) {
rt=null;
dw=null;
data=dataValue;
}
//methods:
public int getData() {
return data;
}
public void setData(int dataValue) {
data = dataValue;
}
public void setrt(Node nextVal) {
rt=nextVal;
}
public void setdw(Node nextVal) {
dw=nextVal;
}
public Node getrt() {
return rt;
}
public Node getdw() {
return dw;
}
I created the following instance:
LinkedList h = new LinkedList<>();
I want to implement a 2D linked list using the built-in linked list class in java. To be able to do this i want to implement my custom node.
No, the node class of LinkedList is private, not exposed, you cannot access it. Except probably through some reflection hack.
And even if you could access the node class, you probably could not replace it with your own class. The LinkedList class is hardcoded to use its own node class.
If you really insisted, you could take the source code of the LinkedList class and modify it to use your node class. Please check if there are any license problems with such an approach before you do it, though. Also my gut feeling is that it’s not worth the trouble compared to writing your custom linked list class from scratch.
Java’s LinkedList is a doubly linked list, so each node has previous and next pointers and reference to data.
You can create a LinkedList of your own for this implementation.
But it looks like there are some basic things which you are doing wrong:
First, as per your implementation, you will be better off with Graph,
because what you are seeking is graph data structure, with each
vertex having four edges.
Second, you should not modify the existing data structures/collection
API provided by Java. If you really want to use different
data-structure, then create it and use it.
And the third and the most important thing to consider is that you
should always try to use the most efficient data-structures to solve a
problem. For example, you can create a 2-D Linkedlist, but ask
yourself, whether is it the most efficient one to store 2-D data? It
might happen that you could have used a matrix or a graph for storing the data.
Also, whenever you create or use a datastructure, consider whether
your application is read/write heavy, based on that you can optimize
storing and fetching of data.
But, it looks like you have just started, and so I would suggest just to go through basic data-structure books or online resources first.
You can also go through below URL which has similar requirement.
custom node class with java's linkedlist class

Working With Stack

it has been to long since i asked here ..
I have this homework which has this Q Remove The Bottom Of The Stack I did it
good but not great ..
but now i have a Q is how to reverse the stack i did it by using another stack
is there a better way
this is what i did :
public static<T> void removeLast(LinkedList<T> st)
{
LinkedList<T> store = new LinkedList<>();
while (!st.eamty()){
store.push(st.pop());
}
store.pop();
while(!store.eamty()){
st.push(store.pop());
}
}
some src I found
Most efficient way to reverse a stack and add to an ArrayList
https://www.careercup.com/question?id=12689669
I'd made the following instead:
public static<T> void removeLast(LinkedList<T> st)
{
return st.removeLast();
}
But this is not a queue meant to be used and is also quite "expensive" operation ...
First of all, LinkedList<T> is not just a Stack. It is a List. In fact, it is a list class with a specific operation to removing the last element. (The removeLast method is defined by the Deque interface which LinkedList implements. The Deque abstraction is a "double ended queue"; i.e. something that can act as both a FIFO and a LIFO - a queue and a stack.)
So if you are able to the fact that this representation of a stack is implemented as a linked list, then the solution is to call that method.
On the other hand, if you are required / restricted to implementing your removeLast using only "stack-like" methods in the LinkedList API, then your approach of popping all elements to a temporary stack is probably as good as you can get.

Should stacks be made from arrays or linked list java?

I have to write a stack for class and while I understand the concept of how a stack works, I wasn't told if they are made using an array or a linked list or something else? How are most stacks created?
ArrayDeque is a solid class implementation of the stack concept. This class has implemented stack in the most efficient way. Please look at the class implementation for the details of various methods.
http://www.docjar.com/html/api/java/util/ArrayDeque.java.html
More specifically, look at public E pollFirst(){...} and public void addFirst(E e)
java.util.Stack is a subclass of java.util.Vector which was a Thread-safe precursor to ArrayList. Hope that helps.
Both options, array and linked list are appropiate.
A linked list may be simpler because you needn't worry about the array size. An array based implementation on the other hand may have better runtime behavior and can be easier to debug (because its easier to view the array than a linked list in the debugger).
Chose whatever you're comfortable with.

what is a more efficient way to implement enqueue in Java

So I have this simple code in java. It enqueue (adds) and element to the end of the queue (implemented by an ArrayList) without changing the original queue. The code:
public class MyQueue<T>{
private List<T> body;
// some constructors and helper functions.
//copy constructor
public Queue(List<T> list){
this.body = list;
}
//this is the function
public MyQueue<T> enqueue(T obj){
List<T> temp = new ArrayList<T>(body);
temp.add(obj);
return new Queue<T>(temp);
}
The whole Idea is to make enqueue faster and more efficient, and again, as you notice, without changing the value of the original queue.
UPDATE For the sake of completing the idea.
1- This is an assignment so university, the skeleton provided is not to be changed, the task is to make the function enqueue faster (i do realize i am copying twice and thats the slow part).
2- As for the helper functions, they are simple:
public T peek(){
if(body.isEmpty()){
thrown new NoSuchElementException();
}
return body.get(0);
}
public int size(){
return body.size();
}
Any ideas? thanks
A queue is a basic data structure and it's hard to make it better than the experts having worked on it. The simplest and fastest general purpose implementation is probably the ArrayDeque and there's hardly anything to improve.
What you're doing is strange at best:
Instead of appending an element, you copy the whole content. Why?
You insert the new element at the highest index, why? This way your poll (dequeue, remove, whatever) must remove the index at element 0, which is slow for ArrayList.
Actually, I have no idea how your poll may look like. In any case, your enqueue doesn't do what I'd expect from a method called like this.
Use a LinkedList instead of an ArrayList. You don't need indexed access in a queue, but you do need fast enqueue/dequeue. If you need indexed access. It isn't really a queue at all. And just use the add() method, don't create a whole new queue every time. Your enqueue() method should return 'this', or void. And don't allow the caller to supply the list: create your own.

Java: Object Oriented Design; LinkedList and Stack

I am writing a BFS and DFS in Java. What I was hoping to do was create one class like this:
/** Preforms BFS and DFS on ...
*/
public class Search{
private XXX toSearch;
// where XXX is an interface of Stack and LinkedList that has
// remove() and add() methods.
public Search(boolean isBFS){
if(isBFS)
toSearch = new LinkedList();
else
toSearch = new Stack();
}
public void preformSearch(){
while(toSearch.size() > 0){
preformSearchOn(toSearch.remove()); // <----- KEY LINE
}
}
private void preformSearchOn(...){...}
}
This class can perform BFS and DFS depending on how it is initialized. What is XXX? I don't think that it exists.
I thought that the entire point of object oriented programing is being able to do cool stuff like this.
What is the cleanest way to handle this?
I think you're looking for the Strategy pattern. The way to do this is not Java specific, or other "cool stuff" for this matter. These types of things transcend languages.
To be more concrete, develop two more classes named BfsStrategy and DfsStrategy. Require that each class implement a certain Strategy interface. Use the class you posted to perform operations on them transparently. (Change class/interface names to be more suitable if you need to.)
For example:
public final class Seeker<E, K> {
private final E structure;
private final SearchStrategy strategy;
public Seeker(final E aStructure, final SearchStrategy aStrategy) {
structure = aStructure;
strategy = aStrategy;
}
public boolean search(K aKey) {
return strategy.search(structure, key); //Pretty generic.
}
}
As far as breadth-first and depth-first searches go, one way to unify both would be to write java.util.Iterator implementations for each one. Let that be your unifying abstraction; it's already part of the JDK.
The common interface is java.util.Queue.
As a first-in-first-out queue you can use (for instance) java.util.LinkedList or java.util.ArrayDeque.
As last-in-first-out queue, you can wrap any Deque using java.util.Collections.asLifoQueue.
Stack, together with is superclass Vector, is deprecated, because it synchronizes all method access, which is often unnecessary. I suspect that's why it doesn't implement Queue.
XXX should be of type java.util.AbstractList as both LinkedList and Stack are derived from it.
But that will not solve you're problem, as the remove() method for each class will behave the same way. In order to get different behaviour you will actual need to call the different removale methods: remove() or pop(). And as method these remove() and pop() are both implemented on java.util.Linkedlist (see Queue interface) there is no need to use the java.util.Stack class either.
You could do call the different methods pop() and remove() with in an if statement, but that would be definitly be an OO anti pateern. An basic OO solution would be to implement 3 classes:
Abstract parent named Search Class
BfsSearch: works with remove() in it's search.
DfsSearch: works with pop() in it's search.
This way, the user of this class can work with Search without needing to know if he is using BfsSearch or DfsSearch.
An even more advanced and flexible OO approach would be to use the Strategy pattern as described by mike. But for simple solutions that don't need this kind of flexibility it might be overkill.
BTW an excelent book on OO design that will explain all these kind of choices and patterns is Larman:
Applying UML and Patterns: An Introduction to Object-Oriented Analysis and Design and Iterative Development (3rd Edition)

Categories