As we know, to push an element at the front of list requires O(1) time. Now consider we want to put (or append) an element at the end of list. What is the complexity of this operation?
Now consider, to put an element at the end of list, we need to traverse the list up to the end (because of not having prev. pointer), requires O(n) time complexity. Will it possible to make this in O(1)?
I did some implementation, while appending value at the end, I am keeping the next place in pointer, where node can be inserted. Check out the following please:
import java.util.*; class List{ int data; List next; List(int data){ this.data = data; } } class Driver{ List head, temp; Driver(){ head = null; temp = head; } void push(int item){ if(head == null){ head = new List(item); temp = head; } else { temp.next = new List(item); temp = temp.next; } } } class AppendInList{ public static void main(String [] args){ Driver obj = new Driver(); obj.push(5); obj.push(66); } } I searched in SO, but I didn't get anything for my satisfaction! Correct me if I did some mistake!