Linked List – clone method

In this post, we will be discussing the clone method in the linked list class and how it will be used to create a copy of the linked list object. The clone method in the linked list overrides the clone method of the Object class.

Method declaration – public Object clone().
What does it do? It will make a shallow copy of the linked list object for which the function is called.
What will it do? – It will return an object of Object class which we will need to be cast to the required type ( in this case, LinkedList type).

Let’s see the things in action with some code.

import java.util.LinkedList;

public class Codekru {

	public static void main(String[] args) {
		LinkedList<String> linkedList = new LinkedList<String>();
		linkedList.add("hi");
		linkedList.add("codekru");

		System.out.println("Original Linked List: " + linkedList);

		LinkedList<String> secondlinkedList = (LinkedList<String>) linkedList.clone();

		System.out.println("Cloned Linked List: " + secondlinkedList);

	}
}

Output –

Original Linked List: [hi, codekru]
Cloned Linked List: [hi, codekru]

So, what is going behind the clone method?
Well, first we make an empty clone, make its first and the last node null, and size zero, and then we run a for loop over the object that has to be cloned and will keep on adding the nodes to the newly made cloned linked list ( We are using add method of the linked list to add elements).

Time complexity –

Here we are majorly doing to operations in the clone method –

  • Running a for loop on to the object which have to be cloned ( So, this will take O(n) time )
  • Using add method in each iteration to add elements in the newly made cloned linked list ( and this will take O(1) time, as add method has a time complexity of O(1) ).

So, overall, time complexity will be O(1) in clone method

We hope that you liked the article. If you have any doubts or concerns, feel free to reach us in comments or mail us at admin@codekru.com

Liked the article? Share this on

Leave a Comment

Your email address will not be published. Required fields are marked *