Open In App

Different methods to initialize a Linked List

Last Updated : 03 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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++




// A complete working C++ program to
// initialize linked list with Copy
// constructor
 
#include <bits/stdc++.h>
using namespace std;
 
// A linked list node
class Node {
public:
    int data;
    Node* next;
    Node(int x)
    {
        data = x;
        next = NULL;
    }
};
 
// A linked list class
class linkedlist {
 
private:
    // head and tail pointer of Node
    Node* head = NULL;
    Node* tail = NULL;
 
public:
    // Non-parameterized constructor
    linkedlist() { head = tail = NULL; }
 
    // Copy constructor to copy the data
    // members of one list into another
    linkedlist(const linkedlist& list)
    {
        if (list.head == NULL) {
            head = tail = NULL;
            return;
        }
 
        // Make a Node pointer temp and
        // initialize it to the head of list
        Node* temp = list.head;
 
        // This loop is creating the new
        // linked list by copying the
        // data of list
        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;
        }
    }
 
    // This function insert create a node
    // with given value and inserts the
    // node at the end of linked list
    void insert(int x)
    {
        // Allocate the temp Node and
        // put x as data into it
        Node* temp = new Node(x);
 
        // Check if the head is NULL
        if (head == NULL) {
            head = temp;
            return;
        }
        else {
            Node* t = head;
            while (t->next != NULL) {
                t = t->next;
            }
            t->next = temp;
        }
    }
 
    // This function prints contents of
    // linked list starting from head
    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;
    }
};
 
// Driver code
int main()
{
    // Creating object l1 of linked list
    linkedlist l1;
 
    l1.insert(1);
    l1.insert(9);
    l1.insert(5);
    l1.insert(7);
 
    cout << "linked list l1 are: ";
    l1.print();
 
    // Copying l1 into l2
    linkedlist l2 = l1;
    cout << "linked list l2 are: ";
    l2.print();
 
    return 0;
}


Java




/*package whatever //do not write package name here */
 
import java.io.*;
 
// A linked list node
class Node {
    int data;
    Node next;
    Node(int x)
    {
        data = x;
        next = null;
    }
}
 
// A linked list class
class LinkedList {
 
    // head and tail pointer of Node
    Node head = null;
    Node tail = null;
 
    // Non-parameterized constructor
    LinkedList() { head = tail = null; }
 
    // Copy constructor to copy the data
    // members of one list into another
    LinkedList(LinkedList list)
    {
        if (list.head == null) {
            head = tail = null;
            return;
        }
 
        // Make a Node pointer temp and
        // initialize it to the head of list
        Node temp = list.head;
 
        // This loop is creating the new
        // linked list by copying the
        // data of list
        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;
        }
    }
 
    // This function insert create a node
    // with given value and inserts the
    // node at the end of linked list
    void insert(int x)
    {
        // Allocate the temp Node and
        // put x as data into it
        Node temp = new Node(x);
 
        // Check if the head is NULL
        if (head == null) {
            head = temp;
            return;
        }
        else {
            Node t = head;
            while (t.next != null) {
                t = t.next;
            }
            t.next = temp;
        }
    }
 
    // This function prints contents of
    // linked list starting from head
    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)
    {
        // Creating object l1 of linked list
        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();
 
        // Copying l1 into l2
        LinkedList l2 = new LinkedList(l1);
        System.out.print("Linked list l2 are: ");
        l2.print();
    }
}


C#




// A complete working C# program to
// initialize linked list with Copy
// constructor
using System;
 
// A linked list node
class Node {
  public int data;
  public Node next;
  public Node(int x)
  {
    data = x;
    next = null;
  }
}
 
// A linked list class
class LinkedList {
 
  // head and tail pointer of Node
  public Node head = null;
  public Node tail = null;
 
  // Non-parameterized constructor
  public LinkedList() { head = tail = null; }
 
  // Copy constructor to copy the data
  // members of one list into another
  public LinkedList(LinkedList list)
  {
    if (list.head == null) {
      head = tail = null;
      return;
    }
 
    // Make a Node pointer temp and
    // initialize it to the head of list
    Node temp = list.head;
 
    // This loop is creating the new
    // linked list by copying the
    // data of list
    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;
    }
  }
 
  // This function insert create a node
  // with given value and inserts the
  // node at the end of linked list
  public void insert(int x)
  {
    // Allocate the temp Node and
    // put x as data into it
    Node temp = new Node(x);
 
    // Check if the head is NULL
    if (head == null) {
      head = temp;
      return;
    }
    else {
      Node t = head;
      while (t.next != null) {
        t = t.next;
      }
      t.next = temp;
    }
  }
 
  // This function prints contents of
  // linked list starting from head
  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()
  {
 
    // Code
    // Creating object l1 of linked list
    LinkedList l1 = new LinkedList();
 
    l1.insert(1);
    l1.insert(9);
    l1.insert(5);
    l1.insert(7);
 
    Console.Write("Linked list l1 are: ");
    l1.print();
 
    // Copying l1 into l2
    LinkedList l2 = new LinkedList(l1);
    Console.Write("Linked list l2 are: ");
    l2.print();
  }
}
 
// This code is contributed by lokeshmvs21.


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;
        }
    }
}
 
// Driver code
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; //copying the list
console.log("linked list l2 are: ");
l2.print();


Python3




# A linked list node
class Node:
    def __init__(self, x):
        self.data = x
        self.next = None
 
# A linked list class
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
     
    # This function insert create a node
    # with given value and inserts the
    # node at the end of linked list
    def insert(self, x):
        # Allocate the temp Node and
        # put x as data into it
        temp = Node(x)
 
        # Check if the head is NULL
        if not self.head:
            self.head = temp
            return
        else:
            t = self.head
            while t.next:
                t = t.next
            t.next = temp
     
    # This function prints contents of
    # linked list starting from head
    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()
 
# Driver code
if __name__ == '__main__':
    # Creating object l1 of linked list
    l1 = LinkedList()
    l1.insert(1)
    l1.insert(9)
    l1.insert(5)
    l1.insert(7)
    print("Linked list l1 are: ", end="")
    l1.print()
 
    # Copying l1 into l2
    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++




// A complete working C++ program to
// initialize linked list with assignment
// operator
 
#include <bits/stdc++.h>
using namespace std;
 
// A linked list node
class Node {
public:
    int data;
    Node* next;
    Node(int x)
    {
        data = x;
        next = NULL;
    }
};
 
// A linked list class
class linkedlist {
private:
    // head and tail pointer of Node
    Node *head, *tail;
 
public:
    // Non-parameterized constructor
    linkedlist() { head = tail = NULL; }
 
    // This is automatically called
    // when '=' operator is
    // used between l1 and l2.
    void operator=(const linkedlist& list)
    {
        if (list.head == NULL) {
            head = tail = NULL;
            return;
        }
 
        // Make a Node pointer temp and
        // initialize it to the head
        // of list
        Node* temp = list.head;
 
        // This loop is creating the new
        // linked list by copying the
        // data of list
        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;
        }
    }
 
    // This function insert create a node
    // with given value and inserts the
    // node at the end of linked list
    void insert(int x)
    {
        // Allocate the temp Node and put
        // x as data into it
        Node* temp = new Node(x);
 
        // Check if the head is NULL
        if (head == NULL) {
 
            // temp will be first node of
            // linkedlist
            head = temp;
            return;
        }
        else {
            Node* t = head;
            while (t->next != NULL) {
                t = t->next;
            }
            t->next = temp;
        }
    }
 
    // This function prints contents of
    // linked list starting from head
    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;
    }
};
 
// Driver code
int main()
{
    // Creating object l1 of linked list
    linkedlist l1;
 
    l1.insert(1);
    l1.insert(9);
    l1.insert(5);
    l1.insert(7);
 
    cout << "linked list l1 are: ";
    l1.print();
 
    linkedlist l2;
 
    // Overloading assignment operator
    // to copy values
    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;
 
// A linked list node
public class Node
{
    public int data;
    public Node next;
 
    public Node(int x)
    {
        data = x;
        next = null;
    }
}
 
// A linked list class
public class LinkedList
{
    private Node head, tail;
 
    // Non-parameterized constructor
    public LinkedList()
    {
        head = tail = null;
    }
 
    // Overloading assignment operator
    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;
        }
    }
 
    // This function insert create a node
    // with given value and inserts the
    // node at the end of linked list
    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;
        }
    }
 
    // This function prints contents of
    // linked list starting from head
    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();
    }
}
 
// Driver code
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();
 
        // Overloading assignment operator to copy values
        l2.CopyFrom(l1);
        Console.Write("linked list l2 are: ");
        l2.Print();
    }
}
//This code is contributed by rudra1807raj


Python3




# A linked list node
class Node:
    def __init__(self, x):
        self.data = x
        self.next = None
 
# A linked list class
class LinkedList:
    def __init__(self):
        self.head = None
        self.tail = None
 
    # Overloading assignment operator
    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
 
    # This function insert create a node
    # with given value and inserts the
    # node at the end of linked list
    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
 
    # This function prints contents of
    # linked list starting from head
    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()
 
# Driver code
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()
 
    # Overloading assignment operator to copy values
    l2.copy_from(l1)
    print("linked list l2 are: ", end="")
    l2.print()
    # This code is contributed by rudra1807raj


Output

linked list l1 are: 1 9 5 7 
linked list l2 are: 1 9 5 7 


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads