What does "this" refer to in Linked List example? - java

So I'm skimming through Cracking the Coding Interview to brush up on some interview stuff and I ran across this linked list implementation, and maybe it's been a while but it's completely going over my head. I understand most of it, except for one specific line, and it's throwing me off. I'll post the code below (for reference, the book doesn't mention language but it appears to be Java.)
class Node {
Node next = null;
int data;
public Node(int d) {
data = d;
}
void appendToTail(int d) {
Node end = new Node(d);
Node n = this;
while(n.next != null) {
n = n.next;
}
n.next = end;
}
}
I'm a little confused on the line: Node n = this - I'm not sure what this is referring to, unless it's talking about next - why not just set it to null in that case?

this refers to a specific instance of an object of a class. Since objects are constructed there can be multiple instances of a class, but using the this keyword allows you to obtain a reference to itself, meaning a reference to the the specific instance of the object whose method is being called.
The linked list is a collection of nodes that are, well, linked together. When you call appendToTail() the node will look at all of the Node objects linked to itself and follow the chain. For it to get a reference to itself to follow its own chain the this keyword is used.
You also ask why null isn't used in this case to initialize n. This would cause a NullPointerException when n.next is first called in the loop constraint, so instead its own reference is used as the starting point for the iteration of the linked-list.
This (pun intended) can be a confusing topic at first, but lets use the example you provided.
Node n = this;
while(n.next != null) {
n = n.next;
}
Let's pretend that there are 4 objects currently linked in our list and for simplicity's sake the Node object that appendToTail() is being called on is the head of the list. Here's the reference value of Node n that's held on each loop iteration from the above snippet.
We're pointing to ourself - this
Pointing to the second item in the linked list. - this.next
Pointing to the following item - this.next.next
Pointing to the last item in the list - this.next.next.next
The loop ended so currently the reference of n = this.next.next.next. We then set n's next value (where n is currently pointing to the end of the linked chain) to the new object we created at the beginning of our method, which makes it the new end of the list. (n.next = end is now equivalent to this.next.next.next.next = end).
Semi-Unnecessary Edit: This is explained in terms of Java. It appears that someone added the C++ tag after I wrote this answer

This is Java.
"this" refers to the specific instance of the class in which the call is being made. In this case, "this" is in reference to the specific class Node you are dealing with. While the variable "end" creates a new and separate version of the Node class which is constructed using the passed int "d".

Since this is a Linked List all Nodes are connected and you have a start Node (root). So when using it it would look like this:
Node root = new Node(6); //need an instance first
root.appendToTail(5);
root.appendToTail(3);
//6->5->3
Since this the nodes are connected I need one start Node and need to check if this has a next node when yes I need to search deeper. When a node did not have a next Node it is the current last one and can add my new Node. So this in Java refers to the current instance of a class. In my example the root Node(because I call root.appendToTail). So the method will search from the root Node (value 6) the next Node without a next Node (the one with value 3) and append it there. If I can get a child reference and would call child3.appendToTail the method would search from child3 instead of starting from my root.
When setting n to null and rewriting the while to go from this.next you would have a problem when the current node you use appendToTail did not have a next Node and an NullPointerException would be thrown.

Node n = this; means n object references to the object which is calling this method.
So method is looping to next object till next object is null and assigning end node to the end.
Lets see
1 -- 2 -- 3 -- 4
*
|
*
obj
you have an obj object that is pointing to node 1. When u call obj.appendToTail(5)
Node end = new Node(d); //new node is created to add to the end.
Node n = this; //local n object is referenced to node 1(or obj)
while(n.next != null) {
n = n.next;
}
//n here is node 4 since there is no next node to 4
n.next = end; //node 5 is tail now
End result:
1 -- 2 -- 3 -- 4 -- 5

As you can see in this code
class Node {
//
void appendToTail( int d ) {
Node *end = new Node( d );
Node n = this;
// ...
}
}
Your class Node has a reference to a Node in it's definition.
The line: Node *end = new Node( d ); means inside a Node there is a reference to another node.
The line Node n = this; means inside a Node the reference to that node itself, is represented by this. Ergo, n is also a reference to said node itself.

Any Node instance can call appendToTail().
Notice howebet, here in fact Node does not append itself to tail of the list, what happens here is that new node is created and added to tail, not the one on which method is invoked.
For this to happen, first we need to find the tail of the list given the current Node.
// n is pointing to current Node
while(n.next != null) {
n = n.next;
}
Once we find node which has next == null, this is tail of the list so we can now append new Node to the tail:
// n points to current tail before next line is invoked
n.next = end;
As to why there is line:
Node n = this;
Well since there is no LinkedList class which maintains reference to the head, you have to be able to iterate from any given Node. That is what happens here, you start iteration from Node on which appendToTail is called, but that Node can be anything at this point, from head to tail.
As a side note, if you implement Linked List by hand, make sure to actually have class LinkedList which will offer methods such as add, get, size, appendToTail and so on, rather then putting these into Node class.

Related

Why use "node.getNext( ) == null" as a convention for defunct node?

This is a code fragment from the book "Data Structures and Algorithms in Java (6th Ed.)" This is method is part of the LinkedPositionalList implementation.
I don't understand exactly what does the line:
"if (node.getNext( ) == null) // convention for defunct node"
is for. I'd appreciate some explanation about its functionality.
// private utilities
/** Validates the position and returns it as a node. */
private Node<E> validate(Position<E> p) throws IllegalArgumentException {
if (!(p instanceof Node)) throw new IllegalArgumentException("Invalid p");
Node<E> node = (Node<E>) p; // safe cast
if (node.getNext( ) == null) // convention for defunct node
throw new IllegalArgumentException("p is no longer in the list");
return node;
}
The implementation in the book you're asking about uses an explicit trailer node that represents a "one past the end" position in the structure. Therefore, all nodes in the list must have a next node. Therefore, if a node's getNext() method returns null that node isn't in the list.
In this case defunct node means a non existent node.
if (node.getNext( ) == null) // convention for defunct node
In this case, the node p has a method called getNext() which can return null, if it does, then it means its the last of the nodes. In other words there is no next node.
This kind of structures, as the name implies, link between each other. getNext() should return a position in memory where the next node is, if such position is not existent then, there is no node there.
Usually node will likely have a method called setNext(Position<E> next) this is the counterpart that saves the position of the next item for this node.
If you read in the book the "Doubly Linked list Implementation" part of chapter 7 explains the defunct position notion as a result of getting rid of any removed position (node) in the list. Because the remove() method implements that the position to be deleted is set to null value.
So the validate() method actually checks if the input position is not removed from the list.. how? once again, by checking if calling getNext() on it would get null value. If so, then it must have been set to null as a deleted position using the remove() method. Therefore it throws an error as the input position p is no longer in the list (since it's a deleted position).
To better understand, just refer to the delete() method there in the book. Here it is from the book:
// Removes the element stored at Position p and returns it (invalidating p).
public E remove(Position<E> p) throws IllegalArgumentException {
Node<E> node = validate(p);
Node<E> predecessor = node.getPrev();
Node<E> successor = node.getNext();
predecessor.setNext(successor);
successor.setPrev(predecessor);
size−−;
E answer = node.getElement();
node.setElement(null); // help with garbage collection
node.setNext(null); // and convention for defunct node
node.setPrev(null);
return answer;
}

Why we can use Node head = null without instantiate the 'head' in Java?

I am reading someone's code. It is about getting input numbers and convert those number into a Linked list. The part of the code is like this:
class Node {
int value;
Node next;
Node() {
next = null;
}
}
Firstly We need to create a head node to indicate head and we let the head be null like this Node head = null.
My limited experiences of java tell me that head is supposed to be a Node type object here. So why we can use Node head = null without instantiate the head?
I think at least I should create Node head = new Node(); then we can use Node head = null;
Anyone can explain it to me?
Node head = null;
This line states that there are no items in the linked list. This is valid in Java and indicates that although head can contain a Node object (or an object of a derived class), it is currently empty.
To add an item to the list, there is likely some code such as:
public void addItemToLinkedList(int value) {
if (head == null) {
head = new Node();
head.value = value;
} else {
...
}
}
So if there is no first Node (when head equals null) then head is created. Otherwise if head already exists, the else block would execute which would look for the end of the list and add another Node.
head is supposed to be a Node type object here
This is optional. Java allows head to be a Node object, or null, to indicate that head is not referencing any nodes at all.
The value of null is special in Java. It is allowed to go wherever an object can go. It indicates that the variable to which you assign null is empty. This is perfectly fine, assuming that the rest of your program deals with null checking.

Implementation of removeFirst() method in SLinkedList in java

I got the following code from one book for implementing a singly linked list. And I don't understand some lines of code in the removeFirst() method, which removes the first node from the LinkedList.
class ListNode{
private String element;
private ListNode next;
public ListNode(){
element = null;
next = null;
}
public ListNode(String s, ListNode n){
element = s;
next = n;
}
//Access method
public String getElement(){
return element;
}
public ListNode getNext(){
return next;
}
//Modify method
public void setNext(ListNode n){
next = n;
}
}
public String removeFirst(){
if(head == null)
return null;
else{
ListNode temp = head;
head = head.getNext();
temp.setNext(null); //Which I don't understand, is it necessary?
size --;
return temp.getElement();
}
}
It seems that the statement temp.setNext(null); can be omitted. So why it is here, does it has anything to do with the garbage colletion in java. Since I am new to Java, any suggestions or ideas?
It depends on the entire implementation of the linked list, which you have not included in your question. However if it is possible for objects to hold a reference to a node even after if has been removed from the list, then the line is necessary.
Suppose we have a long chain of nodes A -> B -> C -> .... Suppose all of these nodes have been removed from the list, but that we still hold onto a reference to A. If all the nodes still held a reference to the next, this would prevent all of the nodes from being garbage collected. Simply setting the next node to be null ensures that only A cannot be garbage collected.
It is likely that implementations of a linked list do mean that references to nodes can be retained. For example, many implementations of Iterator hold a reference to the current node.
Consider this code:
Iterator<String> iterator = list.iterator();
while (i.hasNext()) {
if ("foo".equals(i.next())) {
i.remove();
break;
}
}
// lots more code
This code searches a list for the first occurrence of the String "foo". If it is found, it removes the "foo" from the list and breaks from the loop. The trouble with this is that the Iterator i is still in scope for the remaining code and still holds a reference to a node. This node may be in the middle of the list if the break occurred. Without setting next to be null, this would prevent all subsequent nodes from being garbage collected while i is still in scope, even if the list is cleared.
Note that you should generally make an iterator local to a loop anyway, like this
for (Iterator<String> i = list.iterator();;i.hasNext())
Let us suppose, single linked list of nodes is : A --> B --> C --> D with head node as A. Now, lets go though your removeFirst() method. When it get called, if(head == null) condition doesnt satisfy because our head node "A" is not NULL. Then it execute else statement,
temp = head //take head reference into temporary variable
head = head.getNext(); //As we want to delete first Node which is head so we are setting head to next node (i.e. head --> next) which is Node "B"
Now, to delete A (first Node) we need to break connection between A (which is previous head)--> B (current head) and that will done by
temp.setNext(null); //so out linked list became A B-->C-->D
and then as one node is deleted so in next statement it decreases size of link by size--.
I think we also set the temp reference to NULL as temp=NULL to make deleted node eligible for garbage collection.

Java LinkedStack next = head?

So I have this code for Linked Node Stack (in short Linked Stack) and It confuses me very much! I have an exam tomorrow on that and it confuses me a lot! So take a look:
class Node<T> {
T item; // data in node
Node<T> next = null; // successor node
Node(T item0, Node<T> next0) {
item = item0; next = next0;
}
}
That is easy to understand no problem, we create a class called Node (it's a data structure) which contains an item of type T (can be String, Integer etc..) and another Node called next to indicate the next Node in line. Everything is clear. Off with that!
Now's time for the Stack itself, so here's the code:
class Stack<T> {
private Node<T> head = null; // first node (null if empty)
Stack() {}
Stack(int n) {}
boolean isEmpty() {return(head==null);}
boolean push(T t) {
head = new Node<>(t,head);
return true; // always space available
}
T pop() {
if (head==null) return null;
T t = head.item;
head = head.next;
return t;
}
}
Now here's where I lose my mind! OK so! First off when we initiate the Stack we create a Node with name head okay! Got it and it's null yes! Next, black magic to me is when we use the push(T t) method. So we say head = new Node<>(t, head) okay okay! slow down there fellow! We replace the existing null head with a new Node which contains the data t and as the next node, it carries itself?? so head = data, head(null,null)..? What if we add a 2nd element? it's going to be again head = data, head(data, head(null, null)... ?
Please explain this to me in plain english! :(
The line
head = new Node<>(t,head);
is executed in the order
1) new Node<>(t,head)
2) head = ...
So when you create the new Node object you pass in the old value of head, not a reference to itself.
To be less confusing this line can be rewritten as
Node<T> oldHead = head;
head = new Node<>(t, oldHead);
So when the stack is empty head = null
When we add one item head = (item1, null)
When we add another item head = (item2, (item1, null))
The Node created by push does not contain a reference to itself. When you perform an assignment in Java, the variable being assigned (on the left-hand side of the equal sign) is not altered until after everything on the right side is fully resolved and constructed.
Therefore, at the time that Java executes the Node constructor to create the new head node, the value of head within the Stack object still points to the previous head. The new Node for head is thus created with the new data, plus a reference to the previous head Node. Then, only after the new Node object is fully created (and has a next value pointing to the previous head), the value of head within the Stack object is assigned to the newly-created object.
I think you are over thinking this. So the way a stack works is similar to a linked list. So if you have an empty list, head = null. You got that part right.
So what you are doing when you call push is adding that new node to the top, so it would be the new head node.
head = new Node<>(t,HEAD);
now the new node is at the top of the list and the second argument of Node (which is HEAD)is pointing to the old node that was the head of the linked list.
so on first push, it isn't hard to understand:
first call to push: head = new node(t, NULL) because the old head node is NULL
second call to push: head = new node(t, head) and head (the second argument here) is pointing to what was the old head and is now the next item on the list
When you do head = new Node<>(t, head), you are updating the head of the stack to a Node with Node.item = tand Node.next = oldHead, which in this case is null
because you haven't put anything in it.
If we add 1 element to an empty stack we get Node(data1,null). If we add a second item to the stack we get Node(data2, Node(data1, null))

beginner java code regarding an add method for adding two nodes in a linked list

Im currently having trouble trying to understand linked lists. I have some code that uses nodes and have been asked to use an iterative approach to create a new node with the string parameter stored in it, at the index position specified in the integer parameter. The old node at the index position should follow the newly inserted node.
These are the fields:
// a string that contains the full name on the filesystem of an image file.
private String imageName;
// a reference to the next ImageNode in the linked list.
private ImageNode next;
//temporary node created to start the set of nodes
private ImageNode temp = this;
And this is the code i have written so far: Note that getNext() returns the next node.
private void addIter(String imageFileStr, int pos) {
int count = 0;
while(temp.getNext() != null){
temp = temp.getNext();
count++;
if(count == pos){
temp.getNext() = ???
}
}
}
Is this the right way to go about adding two nodes? If so, this would currently only work if the node needs to be added to the end of the set of current nodes. How would i modify the code so that it allows me to add a node in the middle of set and have the old nodes follow it as stated above ("The old node at the index position should now follow the newly inserted node.")?
And finally, how do i create a variable (x) that is equal to the input from addIter so that i can set temp.getNext() = x? (currently depicted by question marks in the code).
It's impossible to completely answer this without seeing more of your implementation, but here are few things:
temp.getNext() = ??? doesn't make sense, you can't assign to a function call. You will need to add a method setNext(ImageNode node) that sets the next node to the given value.
In your add method, You need to create a new node using the input string (lets call it newNode, find the node currently at pos (lets call it existingNode), then you will need to do a couple things:
Set newNode.next to the node currently after existingNode (or null if it's the end of the list)
Set existingNode.next to newNode.
This will probably end up looking something like this:
public void add(String item, int pos) {
if (pos > length) {
// Probably just throw an out of bounds exception
}
Node existingNode = head;
for (int i = 0; i < pos; i++)
existingNode = existingNode.getNext();
Node newNode = new Node(item);
newNode.setNext(existingNode.getNext());
existingNode.setNext(newNode);
}
Let's assume you have nodes A,B,C and want to insert a new node (D) at pos 3. You will need to iterate through your list up to node 2, i.e. B. Then you save the link to the node following B into a temporary variable, say TempC: Node TempC = B.getNext().
After that you set TempC as the next node after the one you are going to insert: D.setNext(TempC). Then you set D as the next node after B: B.setNext(D). The resulting set will be: A, B, D, C
P.S. here I assume that the first node is 1, not 0.
you definitely need to create a new object and save the data into it. New object must point at the next node where you want to add it and then temp must point at the object.

Categories