Linked list java implementation
Definition: A linked list is a recursive data structure that is either empty (null) or a reference to a node having a generic item and a reference to a linked list.
Structure:
Building a linked list :
Creating Node for each item :
Node head = new Node();
Node child = new Node();
Node child2 = new Node();
Setting the item field in each of the nodes to the desired value :
head.item = "Head";
child.item = "child1";
child2.item = 30;
Building linked list :
head.next = child;
child.next = child2;
Insert:
Insert at the beginning:
Save a link to the list
Node oldHead = head;
create a new node for the beginning
head = new Node();
set the instance variables in the new node
head.item = "Xyz";
head.next = oldHead;
Insert at the end:
save a link to the last node
Node oldlast = head;
create a new node for the end
Node last = new Node();
last.item = "something";
link the new node to the end of the list
oldlast.next = last;
Traversal: Using For loop
for (Node x = head ; x != null; x = x.next)
{
// Process x.item.
}
Structure:
Node record:
class Node<Item>
{
Item item;
Node next;
}
A Node class has two instance : an Item (a parameterized type) and a Node.
Building a linked list :
Creating Node for each item :
Node head = new Node();
Node child = new Node();
Node child2 = new Node();
Setting the item field in each of the nodes to the desired value :
head.item = "Head";
child.item = "child1";
child2.item = 30;
Building linked list :
head.next = child;
child.next = child2;
Insert:
Insert at the beginning:
Save a link to the list
Node oldHead = head;
create a new node for the beginning
head = new Node();
set the instance variables in the new node
head.item = "Xyz";
head.next = oldHead;
Insert at the end:
save a link to the last node
Node oldlast = head;
create a new node for the end
Node last = new Node();
last.item = "something";
link the new node to the end of the list
oldlast.next = last;
Traversal: Using For loop
for (Node x = head ; x != null; x = x.next)
{
// Process x.item.
}
Comments
Post a Comment