I thought of practising some Data Structures with Java.
The first structure that came to my mind was a Linked List.
So, I started writing a Singly Linked List (Single Generified element for the nodes).
For those who are new to generics in java, wait for my next post. I will be explaining generics in the next post.
Here we go ...
Well,
First of all you need a Node Class.
class node<E>
{
E elem;
node<E> next;
}
Here is your node class which has a generic type parameter E.It holds two things:
- 'elem' variable of E type
- 'next' variable of node<E> type (which holds the reference to the next node).
Next, you need a Linked List class (named ll in this article) which will wrap everything.
Basically, each object of Linked List Class contains some basic reference variables which are initialized and changed by the member functions.
class ll<E>
{
node <E> head;
node <E> tail;
node <E> temp;
private int size=0;
} These are the basic member variables needed for all the funtionalities of the class.- node <E> head refers to the head of the Linked List i.e. the first element of the Linked List.
- node <E> tail refers to the tails of the Linked List i.e. the last element of the Linked List.
- node <E> temp is used in various member functions for temporary storage.
- int size is used to store the size of the Linked List. It increases and decreases dynamically as elements are added and removed from the Linked List.
Now lets come to the main part of a class i.e. functions.
add(E Elem) method:
public E addElem(E e)
{
if(head==null)
{
head = new node<E>();
head.elem = e;
head.next = null;
tail=head;
}
else
{
tail.next = new node<E>();
tail = tail.next;
tail.elem = e;
}
this.size++;
return e;
} This method is used to add element at the end of the Linked List. In this method we need to consider two cases:- Case 1: The list is empty. In such a case, we need to create a new node with the provided element and assign it to head variable. Remember to assign the same node to tail as well. You can do this by "tail = head".
- Case 2: The list is not empty and contains at least one element. In such a case, all you need to do is contruct a new node with the provided 'elem', assign it to tail.next and assign the new node to tail.
Go to the next post for More functions.
Great initiative Prateek. The blog looks great and so is its content. Keep posting good implementations of Data Structures :)
ReplyDelete