Different methods to initialize a Linked List
Last Updated :
03 Mar, 2023
Like arrays, a Linked List is a linear data structure. Unlike arrays, linked list elements are not stored at a contiguous location; the elements are linked using pointers. They include a series of connected nodes. Here, each node stores the data and the address of the next node.
There are two methods to copy the linked list into another linked list:
- Copy constructor
- Overloading the ‘Assignment’ operator
Copy Constructor and Linked List
A copy constructor is just like a constructor; it is a member function that is used to initialize a value to an object with the help of another object in the same class. It is easier to use in the C++ programming language when there are several object parameters in the class.
The variables of a Linked list object have been dynamically allocated, then it is required to do a Deep Copy in order to create a copy of the object. Refer to “Shallow Copy and Deep Copy in C++” to know more about it.
For using a copy constructor in the linked list:
- We have used a class Node to create the node of the linked list. A class with the name linkedlist is used here.
- The private part will contain the variables of a pointer-type head and a tail.
- A normal constructor assigns the values to the head and tail parts in the public part and a copy constructor is used to initialize a linked list object with the existing ones.
Below is the implementation of copy constructor.
C++
#include <bits/stdc++.h>
using namespace std;
class Node {
public :
int data;
Node* next;
Node( int x)
{
data = x;
next = NULL;
}
};
class linkedlist {
private :
Node* head = NULL;
Node* tail = NULL;
public :
linkedlist() { head = tail = NULL; }
linkedlist( const linkedlist& list)
{
if (list.head == NULL) {
head = tail = NULL;
return ;
}
Node* temp = list.head;
while (temp != NULL) {
Node* newNode = new Node(temp->data);
if (head == NULL) {
head = newNode;
tail = newNode;
}
else {
tail->next = newNode;
tail = newNode;
}
temp = temp->next;
}
}
void insert( int x)
{
Node* temp = new Node(x);
if (head == NULL) {
head = temp;
return ;
}
else {
Node* t = head;
while (t->next != NULL) {
t = t->next;
}
t->next = temp;
}
}
void print()
{
if (head == NULL) {
cout << "List is empty" << endl;
return ;
}
Node* temp = head;
while (temp != NULL) {
cout << temp->data << " " ;
temp = temp->next;
}
cout << endl;
}
};
int main()
{
linkedlist l1;
l1.insert(1);
l1.insert(9);
l1.insert(5);
l1.insert(7);
cout << "linked list l1 are: " ;
l1.print();
linkedlist l2 = l1;
cout << "linked list l2 are: " ;
l2.print();
return 0;
}
|
Java
import java.io.*;
class Node {
int data;
Node next;
Node( int x)
{
data = x;
next = null ;
}
}
class LinkedList {
Node head = null ;
Node tail = null ;
LinkedList() { head = tail = null ; }
LinkedList(LinkedList list)
{
if (list.head == null ) {
head = tail = null ;
return ;
}
Node temp = list.head;
while (temp != null ) {
Node newNode = new Node(temp.data);
if (head == null ) {
head = newNode;
tail = newNode;
}
else {
tail.next = newNode;
tail = newNode;
}
temp = temp.next;
}
}
void insert( int x)
{
Node temp = new Node(x);
if (head == null ) {
head = temp;
return ;
}
else {
Node t = head;
while (t.next != null ) {
t = t.next;
}
t.next = temp;
}
}
void print()
{
if (head == null ) {
System.out.println( "List is empty" );
return ;
}
Node temp = head;
while (temp != null ) {
System.out.print(temp.data + " " );
temp = temp.next;
}
System.out.println();
}
}
class GFG {
public static void main(String[] args)
{
LinkedList l1 = new LinkedList();
l1.insert( 1 );
l1.insert( 9 );
l1.insert( 5 );
l1.insert( 7 );
System.out.print( "Linked list l1 are: " );
l1.print();
LinkedList l2 = new LinkedList(l1);
System.out.print( "Linked list l2 are: " );
l2.print();
}
}
|
C#
using System;
class Node {
public int data;
public Node next;
public Node( int x)
{
data = x;
next = null ;
}
}
class LinkedList {
public Node head = null ;
public Node tail = null ;
public LinkedList() { head = tail = null ; }
public LinkedList(LinkedList list)
{
if (list.head == null ) {
head = tail = null ;
return ;
}
Node temp = list.head;
while (temp != null ) {
Node newNode = new Node(temp.data);
if (head == null ) {
head = newNode;
tail = newNode;
}
else {
tail.next = newNode;
tail = newNode;
}
temp = temp.next;
}
}
public void insert( int x)
{
Node temp = new Node(x);
if (head == null ) {
head = temp;
return ;
}
else {
Node t = head;
while (t.next != null ) {
t = t.next;
}
t.next = temp;
}
}
public void print()
{
if (head == null ) {
Console.WriteLine( "List is empty" );
return ;
}
Node temp = head;
while (temp != null ) {
Console.Write(temp.data + " " );
temp = temp.next;
}
Console.WriteLine();
}
}
public class GFG {
static public void Main()
{
LinkedList l1 = new LinkedList();
l1.insert(1);
l1.insert(9);
l1.insert(5);
l1.insert(7);
Console.Write( "Linked list l1 are: " );
l1.print();
LinkedList l2 = new LinkedList(l1);
Console.Write( "Linked list l2 are: " );
l2.print();
}
}
|
Javascript
class Node {
constructor(data) {
this .data = data;
this .next = null ;
}
}
class LinkedList {
constructor() {
this .head = null ;
this .tail = null ;
}
insert(x) {
let temp = new Node(x);
if ( this .head === null ) {
this .head = temp;
return ;
}
else {
let t = this .head;
while (t.next !== null ) {
t = t.next;
}
t.next = temp;
}
}
print() {
if ( this .head === null ) {
console.log( "List is empty" );
return ;
}
let temp = this .head;
while (temp !== null ) {
console.log(temp.data);
temp = temp.next;
}
}
}
let l1 = new LinkedList();
l1.insert(1);
l1.insert(9);
l1.insert(5);
l1.insert(7);
console.log( "linked list l1 are: " );
l1.print();
let l2 = new LinkedList();
l2.head = l1.head;
console.log( "linked list l2 are: " );
l2.print();
|
Python3
class Node:
def __init__( self , x):
self .data = x
self . next = None
class LinkedList:
def __init__( self , lst = None ):
self .head = None
self .tail = None
if lst:
temp = lst.head
while temp:
new_node = Node(temp.data)
if not self .head:
self .head = new_node
self .tail = new_node
else :
self .tail. next = new_node
self .tail = new_node
temp = temp. next
def insert( self , x):
temp = Node(x)
if not self .head:
self .head = temp
return
else :
t = self .head
while t. next :
t = t. next
t. next = temp
def print ( self ):
if not self .head:
print ( "List is empty" )
return
temp = self .head
while temp:
print (temp.data, end = " " )
temp = temp. next
print ()
if __name__ = = '__main__' :
l1 = LinkedList()
l1.insert( 1 )
l1.insert( 9 )
l1.insert( 5 )
l1.insert( 7 )
print ( "Linked list l1 are: " , end = "")
l1. print ()
l2 = LinkedList(l1)
print ( "Linked list l2 are: " , end = "")
l2. print ()
|
Output
linked list l1 are: 1 9 5 7
linked list l2 are: 1 9 5 7
Overloading Assignment Operator and Linked List
Assignment operators are used to assign value to a variable.
The left-side operand of the assignment operator is a variable and the right-side operand of the assignment operator is a value. The value on the right side must be of the same data type as the variable on the left side otherwise the compiler will raise an error.
Assignment operator overloading is binary operator overloading. Overloading assignment operator in C++ copies all values of one object to another object.
We can’t directly use the Assignment Operator on objects. The simple explanation for this is that the Assignment Operator is predefined to operate only on built-in Data types. As the class and objects are user-defined data types, so the compiler generates an error, so we have to use the overloading of the assignment operator to copy the linked list into another linked list. Using operator overloading keeps the code short and simple.
Below is the implementation of assignment operator overloading.
C++
#include <bits/stdc++.h>
using namespace std;
class Node {
public :
int data;
Node* next;
Node( int x)
{
data = x;
next = NULL;
}
};
class linkedlist {
private :
Node *head, *tail;
public :
linkedlist() { head = tail = NULL; }
void operator=( const linkedlist& list)
{
if (list.head == NULL) {
head = tail = NULL;
return ;
}
Node* temp = list.head;
while (temp != NULL) {
Node* newNode = new Node(temp->data);
if (head == NULL) {
head = newNode;
tail = newNode;
}
else {
tail->next = newNode;
tail = newNode;
}
temp = temp->next;
}
}
void insert( int x)
{
Node* temp = new Node(x);
if (head == NULL) {
head = temp;
return ;
}
else {
Node* t = head;
while (t->next != NULL) {
t = t->next;
}
t->next = temp;
}
}
void print()
{
if (head == NULL) {
cout << "List is empty" << endl;
return ;
}
Node* temp = head;
while (temp != NULL) {
cout << temp->data << " " ;
temp = temp->next;
}
cout << endl;
}
};
int main()
{
linkedlist l1;
l1.insert(1);
l1.insert(9);
l1.insert(5);
l1.insert(7);
cout << "linked list l1 are: " ;
l1.print();
linkedlist l2;
l2 = l1;
cout << "linked list l2 are: " ;
l2.print();
return 0;
}
|
Javascript
class Node {
constructor(x) {
this .data = x;
this .next = null ;
}
}
class LinkedList {
constructor() {
this .head = this .tail = null ;
}
insert(x) {
let temp = new Node(x);
if ( this .head == null ) {
this .head = temp;
return ;
} else {
let t = this .head;
while (t.next != null ) {
t = t.next;
}
t.next = temp;
}
}
print() {
if ( this .head == null ) {
console.log( "List is empty" );
return ;
}
let temp = this .head;
while (temp != null ) {
console.log(temp.data + " " );
temp = temp.next;
}
}
}
let l1 = new LinkedList();
l1.insert(1);
l1.insert(9);
l1.insert(5);
l1.insert(7);
console.log( "linked list l1 are: " );
l1.print();
let l2 = l1;
console.log( "linked list l2 are: " );
l2.print();
|
Java
import java.util.*;
class Node {
int data;
Node next;
Node( int x)
{
data = x;
next = null ;
}
}
class LinkedList {
private Node head, tail;
LinkedList() { head = tail = null ; }
void assign(LinkedList list)
{
if (list.head == null ) {
head = tail = null ;
return ;
}
Node temp = list.head;
while (temp != null ) {
Node newNode = new Node(temp.data);
if (head == null ) {
head = newNode;
tail = newNode;
}
else {
tail.next = newNode;
tail = newNode;
}
temp = temp.next;
}
}
void insert( int x)
{
Node temp = new Node(x);
if (head == null ) {
head = temp;
return ;
}
else {
Node t = head;
while (t.next != null ) {
t = t.next;
}
t.next = temp;
}
}
void print()
{
if (head == null ) {
System.out.println( "List is empty" );
return ;
}
Node temp = head;
while (temp != null ) {
System.out.print(temp.data + " " );
temp = temp.next;
}
System.out.println();
}
}
public class Main {
public static void main(String[] args)
{
LinkedList l1 = new LinkedList();
l1.insert( 1 );
l1.insert( 9 );
l1.insert( 5 );
l1.insert( 7 );
System.out.print( "linked list l1: " );
l1.print();
LinkedList l2 = new LinkedList();
l2.assign(l1);
System.out.print( "linked list l2: " );
l2.print();
}
}
|
C#
using System;
public class Node
{
public int data;
public Node next;
public Node( int x)
{
data = x;
next = null ;
}
}
public class LinkedList
{
private Node head, tail;
public LinkedList()
{
head = tail = null ;
}
public void CopyFrom(LinkedList otherList)
{
if (otherList.head == null )
{
head = tail = null ;
return ;
}
Node temp = otherList.head;
while (temp != null )
{
Node newNode = new Node(temp.data);
if (head == null )
{
head = newNode;
tail = newNode;
}
else
{
tail.next = newNode;
tail = newNode;
}
temp = temp.next;
}
}
public void Insert( int x)
{
Node temp = new Node(x);
if (head == null )
{
head = temp;
return ;
}
else
{
Node t = head;
while (t.next != null )
{
t = t.next;
}
t.next = temp;
}
}
public void Print()
{
if (head == null )
{
Console.WriteLine( "List is empty" );
return ;
}
Node temp = head;
while (temp != null )
{
Console.Write(temp.data + " " );
temp = temp.next;
}
Console.WriteLine();
}
}
class Program
{
static void Main( string [] args)
{
LinkedList l1 = new LinkedList();
l1.Insert(1);
l1.Insert(9);
l1.Insert(5);
l1.Insert(7);
Console.Write( "linked list l1 are: " );
l1.Print();
LinkedList l2 = new LinkedList();
l2.CopyFrom(l1);
Console.Write( "linked list l2 are: " );
l2.Print();
}
}
|
Python3
class Node:
def __init__( self , x):
self .data = x
self . next = None
class LinkedList:
def __init__( self ):
self .head = None
self .tail = None
def copy_from( self , other_list):
if other_list.head is None :
self .head = self .tail = None
return
temp = other_list.head
while temp is not None :
new_node = Node(temp.data)
if self .head is None :
self .head = new_node
self .tail = new_node
else :
self .tail. next = new_node
self .tail = new_node
temp = temp. next
def insert( self , x):
temp = Node(x)
if self .head is None :
self .head = temp
return
else :
t = self .head
while t. next is not None :
t = t. next
t. next = temp
def print ( self ):
if self .head is None :
print ( "List is empty" )
return
temp = self .head
while temp is not None :
print (temp.data, end = " " )
temp = temp. next
print ()
if __name__ = = "__main__" :
l1 = LinkedList()
l1.insert( 1 )
l1.insert( 9 )
l1.insert( 5 )
l1.insert( 7 )
print ( "linked list l1 are: " , end = "")
l1. print ()
l2 = LinkedList()
l2.copy_from(l1)
print ( "linked list l2 are: " , end = "")
l2. print ()
|
Output
linked list l1 are: 1 9 5 7
linked list l2 are: 1 9 5 7
Similar Reads
Different Ways to Initialize a List in C++ STL
Initializing a list means assigning some initial values to the list elements. In this article, we will learn different methods to initialize the list in C++. Letâs start from the easiest method: The easiest way to initialize a list is by passing the initial values inside an initializer list to its c
3 min read
Move first element to end of a given Linked List
Write a C function that moves first element to end in a given Singly Linked List. For example, if the given Linked List is 1->2->3->4->5, then the function should change the list to 2->3->4->5->1. Algorithm: Traverse the list till last node. Use two pointers: one to store the
14 min read
Second Smallest Element in a Linked List
Given a Linked list of integer data. The task is to write a program that efficiently finds the second smallest element present in the Linked List. Examples: Input : List = 12 -> 35 -> 1 -> 10 -> 34 -> 1Output : The second smallest element is 10.Input : List = 10 -> 5 -> 10Output
15+ min read
Insert a Node after a given Node in Linked List
Given a linked list, the task is to insert a new node after a given node of the linked list. If the given node is not present in the linked list, print "Node not found". Examples: Input: LinkedList = 2 -> 3 -> 4 -> 5, newData = 1, key = 2Output: LinkedList = 2 -> 1 -> 3 -> 4 ->
11 min read
Move the Kth Element in a Doubly Linked List to the End
Given a doubly linked list and an integer K, you need to move the Kth element to the end of the list while maintaining the order of the other elements. Examples: Input: DLL: 2 <-> 6 <-> 3 <-> 8 <-> 11 <-> 23 <-> 7 -> NULL, K = 1Output: 6 <-> 3 <-> 8
13 min read
Print nodes of linked list at given indexes
Given head of two singly linked lists, first one is sorted and the other one is unsorted. The task is to print the elements of the second linked list according to the position pointed out by the data in the first linked list. For example, if the first linked list is 1->2->5, then you have to p
15+ min read
Insertion at the end in circular linked list
A circular linked list is a data structure where each node points to the next, and the last node connects back to the first, creating a loop. Insertion at the end in circular linked list is an important operation. Understanding how to perform this insertion is essential for effectively manage and us
7 min read
Different Ways to Initialize a Variable in C++
Variables are arbitrary names given to the memory location in the system. These memory locations are addressed in the memory. In simple terms, the user-provided names for memory locations are called variables. Additionally, a data type is used to declare and initialize a variable. Suppose we want to
4 min read
How to Create a Linked List in Ruby?
A linked list is a form of linear data structure whereby the elements are not positioned closely together in memory. Each element here instead points to the subsequent one, thus leading to a chain-like arrangement. Creating a linked list in Ruby entails defining an information structure where each n
5 min read
XOR Linked List - A Memory Efficient Doubly Linked List | Set 1
In this post, we're going to talk about how XOR linked lists are used to reduce the memory requirements of doubly-linked lists. We know that each node in a doubly-linked list has two pointer fields which contain the addresses of the previous and next node. On the other hand, each node of the XOR lin
15+ min read