Linked list is a type of data structure that is a collections of nodes where nodes linked to one another using some pointer or reference. linked list is efficient for insertion operations because it uses two pointer head and trail that make it easy to insert something in linked list.
So for insertion O(1) , for deletion O(n) and for searching O(n).
here is a example of single linked list insertion operation in beginning or ending of list :
First create a Node class of any type to set value and next reference of node like this :
private Node<T> nextReference;
private T value;
public Node<T> getNextReference() {
return nextReference;
}
public void setNextReference(Node<T> nextReference) {
this.nextReference = nextReference;
}
public T getValue() {
return value;
}
public void setValue(T value) {
this.value = value;
}
@Override
public int compare(T lhs, T rhs) {
if (lhs == rhs){
return 0;
}else{
return 1;
}
}
Now create a class to perform operation over linked list like this :
public class SingleLinkedList<T>{
private Node<T> head;
private Node<T> trail;
public static int getCount() {
return count;
}
public static void setCount(int count) {
SingleLinkedList.count = count;
}
private static int count = 0;
public void addToLast(T values){
Node<T> newNode = new Node<T>();
newNode.setValue(values);
count++;
if (head == null){
head = newNode;
trail = newNode;
}else{
trail.setNextReference(newNode);
trail = newNode;
}
}
Here we are just creating two nodes for pointer purpose one for head and another for trail of same type T,
we will then send the value in each node from main activity like this :
public class MainActivity extends Activity {
private Button btnAddToLast;
private EditText etValues;
private SingleLinkedList<Integer> singleLinkedList;
private Node<Integer> nodes;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnAddToLast = (Button)findViewById(R.id.btnAddToLast);
etValues = (EditText)findViewById(R.id.etValues);
singleLinkedList = new SingleLinkedList<Integer>();
btnAddToLast.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
singleLinkedList.addToLast(Integer.parseInt(etValues.getText().toString()));
Log.e("linked list values", singleLinkedList.toString());
Log.e("linked list size = ",SingleLinkedList.getCount()+"");
}
});
}
0 Comment(s)