Im in a Java class at school and for the next program we have to edit a list. However there is one part of the instructions I don't understand.
Instructions from Homework:
It has a single data field "head" with the data type of MyNode, which is defined as follows:
public class MyNode<E extends Comparable<E>> {
E element;
MyNode<E> next;
public MyNode(E item) {
element = item;
next = null;
}
}
It contains a non-argument constructor that initialize head to be null.
I don't understand what my instructor means by "head"? Is he referring to the list as the "head"? Any ideas will help. Thank you.
That looks like the implementation of a linked list where each item (or node) contains a link to the next item (or node). Often the first item in a linked list is referred to as the 'head'.
So the instructions are asking you to write a class that contains a variable of type MyNode called head.
Something like this:
public class MyAnswer {
private MyNode head;
public MyAnswer() {
head = null;
}
}
In a linked list, head is the first element or node in the list. The head serves as an entry point to your list as you can reach any element (let's say the nth element) of the list by starting from head and accessing the next field of the node objects n times.
Related
This was asked in an interview.
Can you implement/create an object in java which is similar to Array class in java.
basically we should be able to iterate over the object like we do with arrays and getValue() or putValue() methods should be able to directly work on index of the object created.
ex: below operation should be performed with created object.
int ar[] = new int[5];
for(int i=0; i<5; i++){
ar[i]=i;
}
Hint given was to use linkedlist data structure.
in simple words its the similar like ArrayList class implementation.
can anyone give me an idea how can we do this?
He was asking about nested objects. please read about decorator pattern. please see the below example.
public interface NodeInterface{
// your methods
}
public class Node implements NodeInterface{
private NodeInterface node = null;
// your methods
}
There every node contains nested object of same type. last object that have no object points to a null. you can traverse untill you find a null.
I've asked a similar question before which has been answered, and it has to do with the concept of nodes and linked list. My question can be found by following this link
Problems understanding concept of nodes and linked list
I accepted the answer because it helped me visualize what the linked list would look like and what my Node class would look like.
When you do make the node object, you can then make custom classes to change to value of what that node is storing, as well as retrieving and displaying the data stored in the node.
The node class would look something like this
public class Node{
private int val;
private Node node;
public Node(int val){
this.val=val;
}
public Node(Node node, int val){
this.node = node;
this.val = val;
}
public Node getNext(){
return node;
}
public int getVal(){
return val;
}
}
Obviously you can modify the code to store anything you want, but this is probably what the interviewers were looking for.
Using LinkedList it should looks like:
LinkedList<Integer> linkedList = new LinkedList<>();
for(int i=0; i<5; i++){
linkedList.add(i);
}
However, I'm giving you the link for beginners in which you can lear everything about the java util package. Good luck.
I was given the following Java class definition to implement a single linked list program but I cannot get the full idea. I have written comments in the code poiting out my questions about it.
// ******************************************************************
// Definition of class Node<T>.
// ******************************************************************
public final class Node<T>
{
// This is a class with "generics" where T represents a type.
// A final class cannot be extended.
// A final variable behaves like a constant and can only be initialized at the time it is
// declared or within a constructor.
// I suppose this is the value of the node.
public final T v;
// I do not understand this. How is "next" defined "recursively"?
// Please help me visualize this situation.
// Can this variable indicate the end of the list, maybe with a null value?
public Node<T> next;
// Constructor.
public Node (T val, Node<T> link) {v = val; next = link}
}
// I suppose this is the value of the node.
public final T v;
Yes. Node is a parameterized class where the type of actual data it is holding is called T. So the value of the node is a variable having this type T. We could have a Node<Integer> which holds Integer value but also a Node<String> which would hold a String value. Node will behave the same way.
// I do not understand this. How is "next" defined "recursively"?
// Please help me visualize this situation.
// Can this variable indicate the end of the list, maybe with a null value?
public Node<T> next;
In a linked list, one node points to the next node in the list. This is why it is called "linked" list: there is a chain of elements all linked together. We might say it is defined recursively because one node points the next node, which in turn points to the next-next node, etc.
When the end is reached, there is no next node so it is null: the last element is the one having next = null. Note that there might not be a last element: one node could point to the first one and it would create a circular list.
As an example, let's say you want to build a linked list of 2 integer elements. The first element will be 1 followed by 3. You could write the following:
Node<Integer> firstElement = new Node<>(1, new Node<>(3, null));
// here firstElement.v will be 1 and firstElement.next.v will be 3
I am a couple of java data data structure exercises.
Here is the exercise I am currently doing
Add an array-linked hierarchy to the overall structure. Use the following names: AbstractNodeArrayMyList, NodeArraySorted, and NodeArrayUnsorted
I've already implemented abstract array list, sorted array list, unsorted array list, abstract linked list, sorted linked list, and unsorted linked list.
However I am confused about what this array linked structure or node array is.
I tried doing a google search for an array linked list or structure but all I got was searches that resulted in difference between array and linked list. Can anyone clarify or confirm my initial opinions of what this node array or array linked structure actually is?
When I think of a node, I think of a node in a linked list, something that contains data, and the reference to the node it is connected to, something like
from these lecture notes for ListNode.java
public class ListNode {
int data;
ListNode next;
public ListNode() {
this(0, null);
}
public ListNode(int data) {
this(data, null);
}
public ListNode(int data, ListNode next) {
this.data = data;
this.next = next;
}
}
And when I think about array. I think about something that supports random access, like you can access any element in the array and it would take constant time. So would a node array look something like this? (you define the ListNode as a private inner class) and the outside class would look like
public class NodeArray {
private ListNode[] elementData;
...
private class ListNode {
....
}
}
I didn't think my initial idea was right because the whole idea of the generic array list is that it would work with any type of data. Why have a special class for ArrayNode then?
Linked lists can either be array-based or pointer-based. If you've studied C++, you're probably familiar with pointers. They also exist in Java, but they're controlled by the java compiler behind the scenes, so you don't explicitly reference them. If you think of these structures as arrays vs linked lists, you'll probably confuse yourself. You really should be thinking arrays vs pointers. I know you asked this question in java, but since you don't explicitly use pointers in java, it might make more sense to see an example in C++.
Let's say you have a list classes, ArrayList and PointerList. ArrayList might be set up like the following:
class ArrayClass
{
public:
// Default constructor
ArrayClass();
// Returns the next item in the list using currentPos
// If the end of the list is reached,
// currentPos is reset to begin again.
ItemType getNextItem();
//other methods
private:
int length; // Number of items
ItemType info[MAX_ITEMS]; // Array of items
int currentPos; // List iterator
};
The implementation of getNextItem() using an array-based linked list would look something like this:
ItemType ArrayList::getNextItem()
{
currentPos++;
return info[currentPos];
}
With this implementation, the method returns a copy of the object stored at the index currentPos points to. The index number itself (currentPos) is never revealed to the code that called it, and since the returned object is a copy of the stored object, any changes made to the copy won't automatically be made to the stored version. To store the updated version of the object, the user would have to delete the stored object at info[currentPos], then add the new version in its place. Hopefully this makes sense.
Now let's look at PointerList. It might be defined like so:
class PointerList
{
public:
// Default constructor :
PointerList();
// Returns the next item in the list using currentPos
// If the end of the list is reached,
// currentPos is reset to begin again.
ItemType getNextItem();
//other methods
private:
int length; // Number of nodes on list
NodeType* listData; // List head ptr
NodeType* currentPos; // List iterator
};
The implementation of the pointer-based getNextItem() could look like this:
ItemType PointerArray::getNextItem()
{
ItemType item;
if (currentPos == NULL)
{
currentPos = listData;
}
else
{
currentPos = currentPos->next;
}
item = currentPos->info;
return item;
}
This implementation will return the address of the item in the linked list. Using pointers will return an object by reference, whereas using an array will return an object by value. Any changes made to the object in this implementation will immediately be made to the stored object since the code that called this method has direct access to the stored object.
In both of the above examples, don't worry about ItemType and NodeType. These aren't special data types in C++. They could just as easily be Foo or Car, etc. Also, they can both refer to the same data type.
I hope this makes sense. Let me know if you have further questions.
I am working on a assignment in java that uses a generic type doubly linked lists. I'm sure this is a basic question but since I could not find the answer I thought I would ask. Essentially the implementation of the doubly linked list class is given and all I am required to do is create some nodes. The problem I am having is that the node class is a private static nested class in the list class and I do not understand how I should be using it. The list class looks something like this (leaving out several get and set methods):
public class LinkedList<E> {
private static class Node<E>{
private E element;
private Node<E> previous;
private Node<E> next;
public Node(E e, Node<E> p, Node<E> n) {
element = e;
prev = p;
next = n;
}
}
}
In my driver class I use this:
LinkedList <String> linkedlist = new LinkedList<String>();
LinkedList.Node node = linkedlist.new Node();
node n1 = new node("Amy", null, null);
Using this I get an error saying that LinkedList.Node should be changed to default visibility. Any help is appreciated.
As mentioned by #Lonenebula you don't want to access the Node class from outside of the LinkedList class.
To use the LinkedList, you don't create the node itself, but rather just add the element to the list. The internal code of the LinkedList class will hold all the required details on how to create a new node.
For example to add an element to the List you would have an add(E e) method. This method will then contain the logic to create the node and add it to the List. Within your list class you should already have the next and previous Nodes or have the logic to tell if it is the first or last Node.
At no point should you need to access the Node class from outside of the LinkedList class.
I have this node class, I was wondering how does the program recognize that the Node next is actually the next node? and why would I want to assign it to null please? Detailed explanation would be greatly appreciated.
package LinearNode;
import dataobjects.*;
public class Node
{
public Node next;
public AnyClass obj;
public Node(AnyClass newObj)
{
next = null;
obj = newObj;
}
public void show()
{
System.out.println(obj.getData());
}
public void editNode()
{
obj.editData();
}
public Node getNext()
{
return next;
}
}
A Node is typically used in a linked list, and the node with a null next node is the last one of the list (since it doesn't have any next node).
The next node of a node will be the one you initialize, by doing
someNode.next = someOtherNode;
Note that fields should be private by default, and should almost never be public. Use methods to modify the state of objects.
It's the responsibility of the programmer to properly assemble and use the data structures he chooses. The next node points to a reference of what is assumed to be the 'next' node in the linked list, but Java can't tell you if you've linked them correctly or not. null is often used to represent the end of the list (as opposed to say a circular linked list, in which case head and tail pointers may be used instead of null). Documentation on the linked list data structure can be found on Wikipedia and also here, though the examples are written in C.