Delete linked list Java
Linked List Insert MethodsLinked List Insert Linked List insert methods allow us to insert a Node at a specific place. There are three insert methods based on the position where the new node is inserted.
1. addLastAs the name suggests, the new node is appended at the last position of the Linked list. The Linked List size is increased by 1. The tail points to the newly added Node. Since we have tail Node, the time complexity is O(1) else it would have been O(n). 2. addFirstThe new node is added at the first position of the Linked list. The Linked List size is increased by 1. The head points at the newly added Node. The time complexity is O(1) as there is no traversal of List is involved. 3. addAtThis method has two arguments the Node to insert and an integer index (say k). The node is added at the kth position of the Linked list. The linked list size is increased by 1. In case the element to be added is First or Last then it calls addFirst or addLast respectively. In this operation, we also use another function getNodeAt which is a private member of Our Linked List class. This function takes an integer index as an argument and if the index is valid (i.e. if index>=0 and index Thus in this function traversal of the linked list is required. The time complexity of addAt() function is O(n). Linked List Delete MethodsLinked List Delete Linked List supports three methods to delete nodes.
1. removeLastThis method removes the last element of the Linked list (Provided the list is not an empty list, in which it throws an exception). It moves the tail to point towards the 2nd last element (if any ) and decreases the size by 1. Also, it returns the removed data. Since we have tail Node, therefore, the time complexity is O(1) else it would have been O(n). 2. removeFirstIt removes the first element of the Linked list (Provided the list is not an empty list, in which it throws an exception). This method moves the head to point towards the 2nd element (if any ) and decreases the size by 1. Also, it returns the removed data. The time complexity is of O(1) as there is no traversal of List is involved. 3. removeAtIt takes an Integer index (lets say k) as an argument and if the index is valid it removes the kth element of the Linked list and decreases the size by 1. Also, it returns the removed data. In case the element to be removed is First or Last then it calls removeFirst or removeLast respectively. In this operation, we also use another function getNodeAt which is a private member of the Linked List class. This function takes an integer index as an argument and if the index is valid (i.e. if index>=0 and index Thus in this function traversal of the list is required, therefore, it is of O(n) which makes the time complexity of operation removeAt to be O(n). Output Linked List Insert Delete Implementation in Java |