I'm trying to understand LinkedLists(Single LinkedList to be precise).
I heard/read that delete and add operation will be performed with O(1) complexity and I'm still not getting how to implement with O(1) complexity for these two operation. Below is my implementation in java(NOTE: I don't know c, c++ coding, So I recently started understanding data structures).
public class Node
{
private Integer data = null;
private Node next = null;
private int size = 0;
public Node()
{
}
private Node(Integer data)
{
this.data = data;
}
public boolean add(Integer data)
{
if (null == data) return false;
if (null == this.data)
{
this.data = data;
}
else
{
if (null == this.next)
{
this.next = new Node(data);
}
else
{
this.next.add(data);
}
}
size += 1;
return true;
}
public Integer getDataAt(int index)
{
if (index == 0)
{
return this.data;
}
else
{
return this.next.getDataAt(index - 1);
}
}
public int getSize()
{
return size;
}
}
Please suggest me to edit as of now add(data) to make it O(1) complexity.
xto indexx / 2. In case of linked list, you cannot just "jump", you have to iterate throughx / 2elements.x/2elements?O(logn), while your pseudo binary search would have time complexityO(n).