The Wayback Machine - https://web.archive.org/web/20241120015436/https://www.geeksforgeeks.org/different-methods-to-initialize-a-linked-list/
Open In App

Different methods to initialize a Linked List

Last Updated : 03 Mar, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 


Previous Article
Next Article

Similar Reads

Convert Singly Linked List to XOR Linked List
Prerequisite: XOR Linked List – A Memory Efficient Doubly Linked List | Set 1XOR Linked List – A Memory Efficient Doubly Linked List | Set 2 An XOR linked list is a memory efficient doubly linked list in which the next pointer of every node stores the XOR of previous and next node's address. Given a singly linked list, the task is to convert the gi
9 min read
XOR linked list- Remove first node of the linked list
Given an XOR linked list, the task is to remove the first node of the XOR linked list. Examples: Input: XLL = 4 < – > 7 < – > 9 < – > 7 Output: 7 < – > 9 < – > 7 Explanation: Removing the first node of the XOR linked list modifies XLL to 7 < – > 9 < – > 7 Input: XLL = NULL Output: List Is Empty Approach: Th
11 min read
Remove all occurrences of one Linked list in another Linked list
Given two linked lists head1 and head2, the task is to remove all occurrences of head2 in head1 and return the head1. Examples: Input: head1 = 2 -> 3 -> 4 -> 5 -> 3 -> 4, head2 = 3 -> 4Output: 2 -> 5Explanation: After removing all occurrences of 3 -> 4 in head1 output is 2 -> 5. Input: head1 = 3 -> 6 -> 9 -> 8 -
9 min read
Count occurrences of one linked list in another Linked List
Given two linked lists head1 and head2, the task is to find occurrences of head2 in head1. Examples: Input: Head1 = 1->2->3->2->4->5->2->4, Head2 = 2->4Output: Occurrences of head2 in head1: 2 Input: Head1 = 3->4->1->5->2, Head2 = 3->4Output: Occurrences of Head2 in Head1: 1 Approach 1: To solve the problem us
15 min read
When is Doubly Linked List more Efficient than Singly Linked List?
Did you know there are some cases where a Doubly Linked List is more efficient than a Singly Linked List, even though it takes more memory compared to a Singly Linked List? What are those Cases? Well, we will discuss that in the following article, But first, let's talk about Singly and linked lists: What is a Singly Linked List?A singly linked list
4 min read
XOR Linked List - Reverse a Linked List in groups of given size
Given a XOR linked list and an integer K, the task is to reverse every K nodes in the given XOR linked list. Examples: Input: XLL = 7< – > 6 < – > 8 < – > 11 < – > 3, K = 3 Output: 8 < – > 6 < – > 7 < – > 3 < – > 11 Explanation: Reversing first K(= 3) nodes modifies the Linked List to 8 < – > 6
13 min read
XOR Linked List: Remove last node of the Linked List
Given an XOR linked list, the task is to delete the node at the end of the XOR Linked List. Examples: Input: 4<–>7<–>9<–>7Output: 4<–>7<–>9Explanation: Deleting a node from the end modifies the given XOR Linked List to 4<–>7<–>9 Input: 10Output: List is emptyExplanation: After deleting the only node present
15+ min read
Is two way linked list and doubly linked list same?
Yes, a two-way linked list and a doubly linked list are the same. Both terms refer to a type of linked list where each node contains a reference to the next node as well as the previous node in the sequence. The term “two-way” emphasizes the ability to move in both directions through the list, while “doubly” highlights that there are two links per
3 min read
XOR Linked List - Pairwise swap elements of a given linked list
Given a XOR linked list, the task is to pairwise swap the elements of the given XOR linked list . Examples: Input: 4 <-> 7 <-> 9 <-> 7Output: 7 <-> 4 <-> 7 <-> 9Explanation:First pair of nodes are swapped to formed the sequence {4, 7} and second pair of nodes are swapped to form the sequence {9, 7}. Input: 1 <
12 min read
XOR linked list: Reverse last K nodes of a Linked List
Given a XOR Linked List and a positive integer K, the task is to reverse the last K nodes in the given XOR linked list. Examples: Input: LL: 7 <–> 6 <–> 8 <–> 11 <–> 3 <–> 1, K = 3Output: 7<–>6<–>8<–>1<–>3<–>11 Input: LL: 7 <–> 6 <–> 8 <–> 11 <–> 3 <–> 1 <–
14 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 linked list requires only a single pointer field, whi
15+ min read
Linked List of Linked List
Linked list of linke­d list, also known as nested linke­d lists, is a type of Linked List where each main node stores another full linked list. This structure­ beats old, plain linked lists. It gives way more­ flexibility to store and manage comple­x data. In this article we will learn about the basics of Linked List of Linked List, how to create L
9 min read
XOR Linked List – A Memory Efficient Doubly Linked List | Set 2
In the previous post, we discussed how a Doubly Linked can be created using only one space for the address field with every node. In this post, we will discuss the implementation of a memory-efficient doubly linked list. We will mainly discuss the following two simple functions. A function to insert a new node at the beginning.A function to travers
10 min read
Create new linked list from two given linked list with greater element at each node
Given two linked list of the same size, the task is to create a new linked list using those linked lists. The condition is that the greater node among both linked list will be added to the new linked list.Examples: Input: list1 = 5->2->3->8list2 = 1->7->4->5Output: New list = 5->7->4->8Input: list1 = 2->8->9->3li
8 min read
Difference between Singly linked list and Doubly linked list
Introduction to Singly linked list : A singly linked list is a set of nodes where each node has two fields 'data' and 'link'. The 'data' field stores actual piece of information and 'link' field is used to point to next node. Basically the 'link' field stores the address of the next node.  Introduction to Doubly linked list : A Doubly Linked List (
2 min read
Check if a linked list is Circular Linked List
Given the head of a singly linked list, the task is to find if given linked list is circular or not. A linked list is called circular if its last node points back to its first node. Note: The linked list does not contain any internal loops. Example: Input: LinkedList: 2->4->6->7->5 Output: trueExplanation: As shown in figure the first a
12 min read
Javascript Program To Merge A Linked List Into Another Linked List At Alternate Positions
Given two linked lists, insert nodes of the second list into the first list at alternate positions of the first list. For example, if first list is 5->7->17->13->11 and second is 12->10->2->4->6, the first list should become 5->12->7->10->17->2->13->4->11->6 and second list should become empty. The
3 min read
Insert a linked list into another linked list
Given two linked lists, head1 and head2 of sizes m and n respectively. The task is to remove head1's nodes from the ath node to the bth node and insert head2 in their place. Examples: Input: a = 3, b = 4head1: 10 -> 11 -> 12 -> 13 -> 14 -> 15, head2: 100 -> 101 -> 102 -> 103Output: 10 -> 11 -> 12 -> 100 -> 101 -
10 min read
Convert singly linked list into circular linked list
Given a singly linked list, the task is to convert it into a circular linked list. Examples: Input: head: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> NULLOutput: Explanation: Singly linked list is converted to circular by pointing last node to head. Input: head: 2 -> 4 -> 6 -> 8 -> 10 -> 12 -> NULLOutput: Explanation: Singly l
11 min read
Merge a linked list into another linked list at alternate positions
Given two singly linked lists, The task is to insert nodes of the second list into the first list at alternate positions of the first list and leave the remaining nodes of the second list if it is longer. Example: Input: head1: 1->2->3 , head2: 4->5->6->7->8Output: head1: 1->4->2->5->3->6 , head2: 7->8 Input: hea
8 min read
How to initialize Array of objects with parameterized constructors in C++
Array of Objects: When a class is defined, only the specification for the object is defined; no memory or storage is allocated. To use the data and access functions defined in the class, you need to create objects. Syntax: ClassName ObjectName[number of objects]; Different methods to initialize the Array of objects with parameterized constructors:
6 min read
Efficient way to initialize a priority queue
STL Priority Queue is the implementation of Heap Data Structure. By default, it's a max heap, and can be easily for primitive data types. There are some important applications of it which can be found in this article. Priority queue can be initialized in two ways either by pushing all elements one by one or by initializing using their constructor.
7 min read
How to Initialize and Compare Strings in Java?
String is one of the most basic data types and it is widely used in storing and manipulating pieces of text. One of the fundamental features of strings in Java is their immutability that is once a string is created, it will never be changed. Immutability creates two general ways of initialization with strings in Java using the String Pool. This art
5 min read
Analysis of Different Methods to find Prime Number in Python
If you participate in competitive programming, you might be familiar with the fact that questions related to Prime numbers are one of the choices of the problem setter. Here, we will discuss how to optimize your function which checks for the Prime number in the given set of ranges, and will also calculate the timings to execute them. Going by defin
7 min read
Count digits in an integer (4 Different Methods)
Given a number N, the task is to return the count of digits in this number. In this post, we are going to discuss 4 different programs to do the same. Example: Input: N = 1567Output: 4Explanation: There are 4 digits in 1567, which are 1, 5, 6 and 7. Input: N = 255Output: 3Explanation: The are 3 digits in 256, which are 2, 5 and 5. Input: N = 58964O
11 min read
Deletion at different positions in a Circular Linked List
tGiven a Circular Linked List. The task is to write programs to delete nodes from this list present at: First position.Last Position.At any given position [Tex]i [/Tex].Deleting first node from Singly Circular Linked List Examples: Input : 99->11->22->33->44->55->66 Output : 11->22->33->44->55->66 Input : 11->22-
15+ min read
How is Blockchain Different From a Linked List?
The article focuses on discussing the differences between Linked List and a Blockchain. Here, we will discuss the following points: What is Linked List?What is Blockchain?Similarities Between Linked List And Blockchain.Linked List vs Blockchain.Let's discuss each of these topics in detail. What is Linked List?A linked list is a linear data structur
5 min read
Construct a Maximum Sum Linked List out of two Sorted Linked Lists having some Common nodes
Given two sorted linked lists, construct a linked list that contains maximum sum path from start to end. The result list may contain nodes from both input lists. When constructing the result list, we may switch to the other input list only at the point of intersection (which mean the two node with the same value in the lists). You are allowed to us
14 min read
Create a linked list from two linked lists by choosing max element at each position
Given two linked list of equal sizes, the task is to create new linked list using those linked lists where at every step, the maximum of the two elements from both the linked lists is chosen and the other is skipped. Examples: Input: list1 = 5 -> 2 -> 3 -> 8 -> NULL list2 = 1 -> 7 -> 4 -> 5 -> NULL Output: 5 -> 7 -> 4
11 min read
Construct a Doubly linked linked list from 2D Matrix
Given a 2D matrix, the task is to convert it into a doubly-linked list with four pointers that are next, previous, up, and down, each node of this list should be connected to its next, previous, up, and down nodes.Examples: Input: 2D matrix 1 2 3 4 5 6 7 8 9 Output: Approach: The main idea is to construct a new node for every element of the matrix
15+ min read
three90RightbarBannerImg