This is a general question, maybe about OOP concept. I am just starting with DS implementation in JAVA. I am trying to implement Linked List and on all online rsources, I see a similar practice:
- Make a node class.
- Make a class Linked List that has a node object.
Similarly I saw for stack, queues and trees. My question is, if I implement LinkedList by only having one class that looks like below:
class LinkList {
int data;
LinkList next; }
I am still able to do all the operations. So the concept of having a second class that contains a root or a header is only for OOP purpose or something else? I wrote the following code and it works all well without the need to have a header pointer. I use a references variable in all the methods and the main class's object still keeps the track of the head.
/* package codechef; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
class LinkList {
int data;
LinkList next;
LinkList(){
data = 0;
next = null;
}
LinkList(int data) {
this.data = data;
next = null;
}
LinkList insertAtBegin(int data){
LinkList newBegin = new LinkList(data);
newBegin.next = this;
return newBegin;
}
void insertAtPlace(int data, int insertData){
LinkList newNode = new LinkList(insertData);
LinkList iterator = this;
while(iterator!=null && iterator.data!=data){
iterator = iterator.next;
}
if(iterator.data == data)
{
newNode.next = iterator.next;
iterator.next = newNode;
}
}
void insertAtLast(int data) {
if(next == null){
next = new LinkList(data);
}
else{
next.insertAtLast(data);
}
}
}
/* Name of the class has to be "Main" only if the class is public. */
class Codechef
{
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
LinkList linkList = new LinkList(6);
linkList.insertAtLast(5);
linkList.insertAtLast(3);
linkList.insertAtLast(2);
linkList.insertAtLast(1);
linkList = linkList.insertAtBegin(10);
LinkList iterator = linkList;
while(iterator!=null){
System.out.print(iterator.data);
iterator = iterator.next;
}
System.out.print("\n");
linkList.insertAtPlace(5,-1);
iterator = linkList;
while(iterator!=null){
System.out.print(iterator.data);
iterator = iterator.next;
}
}
}