Reputation: 800
I am currently learning to implement linked list in Java when I came across sample code which counts nodes in a linked list
class ListNodes { int item; ListNodes next; }
int count(Node ptr_start)
{
int c=0;
Node ptr = new Node();
ptr = ptr_start;
while(ptr != null)
{
c++;
ptr = ptr.next;
}
return c;
}
I have few questions here what exactly is
ListNodes next;
and 'ListNodes' has same name as that of it's class ?
what is
ptr = ptr_start; i think it's for pointer to start with a value , but can it have other values other than 'ptr_start' ? and
ptr = ptr.next;
I think it moves to next pointer but 'next' moves it to other pointer , it 'next' Java defined or user defined thing? It sort of seems like I don't understand anything is this code , please help?
Upvotes: 1
Views: 1797
Reputation:
class ListNodes {
int item;
ListNodes next;
}
int count(Node ptr_start)
{
int c=0;
Node ptr = new Node(); // IT CREATES A NEW NODE NAMED ptr.
ptr = ptr_start; //ptr_start is a node which is coming from the other class name. and ptr is
// has became same as ptr_start (the first node)
while(ptr != null) // this loop will go as long as the ptr != null.
{
c++;
ptr = ptr.next; //ptr = ptr.next means ptr will become the next node in this line.
}
return c;
}
I hope I answered some of your confusion. Also, read the oracle documentation for better understanding. :)
Upvotes: 3
Reputation: 3145
ListNodes is indeed the name of the class, and also of it's instantiated objects. "Next" simply refers to the next ListNodes in the chain, and is thus of the type ListNodes.
I do NOT like how the class name is in plural, by the way.
ptr is kept as a reference to the ListNodes (again, aaaaaaargh with the plural!) we are currently pointing at, as we are swooping through the list. So the first thing we do in this method is to set ptr to ptr_start, as ptr_start is the first ListNodes in the list, and we want to start counting from the very beginning.
Then what happens is we keep moving ptr onward one step at a time, for as long as there are new nodes to visit.
Upvotes: 1
Reputation: 2551
First if you are new to linked list please refer to this link it has a good explanation :
http://docs.oracle.com/javase/7/docs/api/java/util/LinkedList.html
second ListNodes next
is the the items inside the listNode every item is called next
.
third what is ptr = ptr_start;
is the pointer to the linked list ptr is set at the beginning of the linkedList.
ptr = ptr.next;
is to increase the pointer and to tell the linkedlist to jump to the next item
Upvotes: 1