Open In App

Why Linked List is implemented on Heap memory rather than Stack memory?

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

Pre-requisite: 

Linked List Data Structure
Stack vsHeap Memory Allocation

The Linked List is a linear data structure, in which the elements are not stored at contiguous memory locations. The elements in a linked list are linked using pointers. It is implemented on the heap memory rather than the stack memory. This article discusses the reason behind it.

Stack vs Heap Memory

The computer’s memory is divided into heap and stack memory segments. Stack memory segment is relatively small so it is mainly used for operations like recursion or control jump statements like goto statement. Due to the small size of the stack segment, it is not used for deep recursion levels as it may throw a stack overflow error.

On the other hand, a linked list has the major advantage of dynamically expanding itself when needed without worrying about memory consumption. This is the reason why heap is preferred for storing linked list-object.

Why linked list is not stored in stack memory?

The question of why one cannot make a linked list with stack memory is due to the scope rules and automatic memory management on the stack. The basic idea of a linked list is to link nodes together based on their memory address. If each node is created on the stack then those nodes will be deleted after they go out of scope, so even if the user keeps pointers to their memory address it is not safe to assume that they won’t be overwritten by something else.

The linked list can be implemented on the stack memory as well. Below is the C++ implementation of creating a linked list in stack memory:

C++




// C++ program to implement
// linked list in stack
#include <iostream>
using namespace std;
 
// Structure of the linked list
struct Node {
    int data;
    struct Node* next;
 
    // Constructor
    Node(int x)
    {
        data = x;
        next = NULL;
    }
}* head = NULL;
 
// Function to print the linked list
void printLinkedList(Node* head)
{
    struct Node* temp = head;
 
    // Traversing linked list
    while (temp) {
        cout << temp->data << " ";
        temp = temp->next;
    }
}
 
// Driver code
int main()
{
    // Creation of linked list in stack
    struct Node first = Node(1);
    struct Node second = Node(2);
    struct Node third = Node(3);
    struct Node fourth = Node(4);
 
    head = &first;
 
    // 1 -> 2 -> 3 -> 4
    first.next = &second;
    second.next = &third;
    third.next = &fourth;
    fourth.next = NULL;
 
    // Printing the elements of
    // a linked list
    printLinkedList(head);
 
    return 0;
}


Java




// Java program to implement
// linked list in stack
 
import java.util.*;
 
class GFG{
 
// Structure of the linked list
static class Node {
    int data;
    Node next;
 
    // Constructor
    Node(int x)
    {
        data = x;
        next = null;
    }
};
static Node head = null;
 
// Function to print the linked list
static void printLinkedList(Node head)
{
    Node temp = head;
 
    // Traversing linked list
    while (temp!=null) {
        System.out.print(temp.data+ " ");
        temp = temp.next;
    }
}
 
// Driver code
public static void main(String[] args)
{
    // Creation of linked list in stack
    Node first = new Node(1);
    Node second = new  Node(2);
    Node third = new Node(3);
    Node fourth = new Node(4);
 
    head = first;
 
    // 1.2.3.4
    first.next = second;
    second.next = third;
    third.next = fourth;
    fourth.next = null;
 
    // Printing the elements of
    // a linked list
    printLinkedList(head);
 
}
}
 
// This code contributed by shikhasingrajput


Python3




# Python program to implement
# linked list in stack
 
# Node class
class Node:
    def __init__(self, x):
        self.data = x
        self.next = None
 
 
# Initialize head to None
head = None
 
# Function to print the linked list
def printLinkedList(head):
    temp = head
 
    # Traversing linked list
    while temp:
        print(temp.data, end=" ")
        temp = temp.next
 
# Driver code
if __name__ == '__main__':
 
    # Creation of linked list in stack
    first = Node(1)
    second = Node(2)
    third = Node(3)
    fourth = Node(4)
 
    head = first
 
    # 1 -> 2 -> 3 -> 4
    first.next = second
    second.next = third
    third.next = fourth
    fourth.next = None
 
    # Printing the elements of
    # a linked list
    printLinkedList(head)
 
    # This code is contributed by surajrasr7277.


C#




// C# program to implement
// linked list in stack
using System;
using System.Collections.Generic;
 
public class GFG{
 
  // Structure of the linked list
  class Node {
    public int data;
    public Node next;
 
    // Constructor
    public Node(int x)
    {
      data = x;
      next = null;
    }
  };
  static Node head = null;
 
  // Function to print the linked list
  static void printList(Node head)
  {
    Node temp = head;
 
    // Traversing linked list
    while (temp!=null) {
      Console.Write(temp.data+ " ");
      temp = temp.next;
    }
  }
 
  // Driver code
  public static void Main(String[] args)
  {
 
    // Creation of linked list in stack
    Node first = new Node(1);
    Node second = new  Node(2);
    Node third = new Node(3);
    Node fourth = new Node(4);
 
    head = first;
 
    // 1.2.3.4
    first.next = second;
    second.next = third;
    third.next = fourth;
    fourth.next = null;
 
    // Printing the elements of
    // a linked list
    printList(head);
 
  }
}
 
// This code is contributed by shikhasingrajput


Javascript




<script>
// Javascript program to implement
// linked list in stack
 
// Structure of the linked list
class Node {
 
    // Constructor
    constructor(x) {
        this.data = x;
        this.next = null;
    }
}
 
// Function to print the linked list
function printLinkedList(head) {
    let temp = head;
 
    // Traversing linked list
    while (temp) {
        document.write(temp.data + " ");
        temp = temp.next;
    }
}
 
// Driver code
 
// Creation of linked list in stack
let first = new Node(1);
let second = new Node(2);
let third = new Node(3);
let fourth = new Node(4);
 
head = first;
 
// 1 -> 2 -> 3 -> 4
first.next = second;
second.next = third;
third.next = fourth;
fourth.next = null;
 
// Printing the elements of
// a linked list
printLinkedList(head);
 
// This code is contributed by gfgking.
</script>


Output:

1 2 3 4 

Time Complexity: O(n), where n is the number of nodes in the linked list.

Space Complexity: O(1), as no extra space is required.

Condition when linked list implementation on the stack will not work:

The above code won’t work if we write the logic of the creation of a linked list in a separate function and the logic of printing the elements of the linked list in a separate function. Below is its C++ implementation of the above concept:

C++




// C++ program to implement
// the above approach
#include <iostream>
using namespace std;
 
// Structure of the linked list
struct Node {
    int data;
    struct Node* next;
 
    Node(int x)
    {
        data = x;
        next = NULL;
    }
}* head = NULL;
 
// Function to return the head pointer
// of the created linked list
Node* CreateLinkedList()
{
    struct Node first = Node(1);
    struct Node second = Node(2);
    struct Node third = Node(3);
    struct Node fourth = Node(4);
 
    head = &first;
 
    // 1->2->3->4
    first.next = &second;
    second.next = &third;
    third.next = &fourth;
    fourth.next = NULL;
 
    return head;
}
 
// Function to print the linked list
void printLinkedList(Node* head)
{
    struct Node* temp = head;
 
    // Traversing linked list
    while (temp) {
        cout << temp->data << " ";
        temp = temp->next;
    }
}
 
// Driver Code
int main()
{
    struct Node* head = CreateLinkedList();
    printLinkedList(head);
    return 0;
}


Java




// Java program to implement
// the above approach
 
import java.util.*;
 
class GFG{
 
// Structure of the linked list
static class Node {
    int data;
    Node next;
 
    Node(int x)
    {
        data = x;
        next = null;
    }
}
static Node head = null;
 
// Function to return the head pointer
// of the created linked list
static Node CreateLinkedList()
{
    Node first = new Node(1);
    Node second = new Node(2);
    Node third = new Node(3);
    Node fourth = new Node(4);
 
    head = first;
 
    // 1.2.3.4
    first.next = second;
    second.next = third;
    third.next = fourth;
    fourth.next = null;
 
    return head;
}
 
// Function to print the linked list
static void printLinkedList(Node head)
{
    Node temp = head;
 
    // Traversing linked list
    while (temp!=null) {
        System.out.print(temp.data+ " ");
        temp = temp.next;
    }
}
 
// Driver Code
public static void main(String[] args)
{
    Node head = CreateLinkedList();
    printLinkedList(head);
}
}
 
// This code is contributed by 29AjayKumar


C#




// C# program to implement
// the above approach
 
using System;
 
public class GFG{
 
  // Structure of the linked list
  class Node {
    public int data;
    public Node next;
 
    public Node(int x)
    {
      data = x;
      next = null;
    }
  }
  static Node head = null;
 
  // Function to return the head pointer
  // of the created linked list
  static Node CreateList()
  {
    Node first = new Node(1);
    Node second = new Node(2);
    Node third = new Node(3);
    Node fourth = new Node(4);
 
    head = first;
 
    // 1.2.3.4
    first.next = second;
    second.next = third;
    third.next = fourth;
    fourth.next = null;
 
    return head;
  }
 
  // Function to print the linked list
  static void printList(Node head)
  {
    Node temp = head;
 
    // Traversing linked list
    while (temp != null) {
      Console.Write(temp.data + " ");
      temp = temp.next;
    }
  }
 
  // Driver Code
  public static void Main(String[] args)
  {
    Node head = CreateList();
    printList(head);
  }
}
 
// This code is contributed by shikhasingrajput


Javascript




<script>
 
// javascript program to implement
// the above approach    // Structure of the linked list
     class Node
     {
        constructor( x) {
            this.data = x;
            this.next = null;
        }
    }
 
    var head = null;
 
    // Function to return the head pointer
    // of the created linked list
    function CreateLinkedList() {
        var first = new Node(1);
        var second = new Node(2);
        var third = new Node(3);
        var fourth = new Node(4);
 
        head = first;
 
        // 1.2.3.4
        first.next = second;
        second.next = third;
        third.next = fourth;
        fourth.next = null;
 
        return head;
    }
 
    // Function to print the linked list
    function printLinkedList( head) {
        var temp = head;
 
        // Traversing linked list
        while (temp != null) {
            document.write(temp.data + " ");
            temp = temp.next;
        }
    }
 
    // Driver Code
        var head = CreateLinkedList();
        printLinkedList(head);
         
// This code contributed by shikhasingrajput
</script>


Python3




# Structure of the linked list
class Node:
    def __init__(self, x):
        self.data = x
        self.next = None
 
head = None
 
# Function to return the head pointer of the created linked list
def createLinkedList():
    first = Node(1)
    second = Node(2)
    third = Node(3)
    fourth = Node(4)
 
    global head
    head = first
 
    # 1.2.3.4
    first.next = second
    second.next = third
    third.next = fourth
    fourth.next = None
 
    return head
 
# Function to print the linked list
def printLinkedList(head):
    temp = head
 
    # Traversing linked list
    while(temp != None):
        print(temp.data, end=" ")
        temp = temp.next
 
# Driver Code
head = createLinkedList()
printLinkedList(head)


Time Complexity: O(n),The time complexity of this algorithm is O(n) because it iterates through the linked list, traversing each node only once. 
Space Complexity: O(1),The space complexity is O(1) since no extra space is used.
Explanation:

The above code gives the verdict as SEGMENTATION FAULT. The reason behind it is that during the creation of the linked list in the stack memory, all the objects created by a function will be disappeared as the stack frame is popped whenever the function ends or returns. Refer to this article to know the reason behind the popping of stack frame whenever function ends.

Why linked list is stored in heap memory?

In a linked list, when there is a need to store more data, we can allocate the memory at run-time by using malloc or a new function in C/ C++. So dynamic memory allocation reserve size from heap area, therefore, a linked list is stored in heap memory.
If there is a need to store linked lists in the stack area then implement linked lists without using malloc or a new function.

Below is the C++ program to show how to implement a linked list in heap memory without throwing segmentation fault error:

C++




// C++ program to implement
// the above approach
#include <iostream>
using namespace std;
 
// Structure of the linked list
struct Node {
    int data;
    struct Node* next;
};
struct Node* head = NULL;
 
// Function to create nodes of
// the linked list
void CreateLinkedList(int new_data)
{
    struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
    new_node->data = new_data;
    new_node->next = head;
    head = new_node;
}
 
// Function to print the linked list
void printLinkedList()
{
    struct Node* temp;
    temp = head;
 
    // Traversing linked list
    while (temp != NULL) {
        cout << temp->data << " ";
        temp = temp->next;
    }
}
 
// Driver Code
int main()
{
    CreateLinkedList(1);
    CreateLinkedList(2);
    CreateLinkedList(3);
    CreateLinkedList(4);
    printLinkedList();
    return 0;
}


Java




// Java program to implement
// the above approach
import java.util.*;
public class GFG{
 
// Structure of the linked list
static class Node {
    int data;
    Node next;
};
static Node head = null;
 
// Function to create nodes of
// the linked list
static void CreateLinkedList(int new_data)
{
    Node new_node = new Node();
    new_node.data = new_data;
    new_node.next = head;
    head = new_node;
}
 
// Function to print the linked list
static void printLinkedList()
{
    Node temp;
    temp = head;
 
    // Traversing linked list
    while (temp != null) {
        System.out.print(temp.data+ " ");
        temp = temp.next;
    }
}
 
// Driver Code
public static void main(String[] args)
{
    CreateLinkedList(1);
    CreateLinkedList(2);
    CreateLinkedList(3);
    CreateLinkedList(4);
    printLinkedList();
}
}
 
// This code is contributed by 29AjayKumar


C#




// C# program to implement
// the above approach
using System;
using System.Collections.Generic;
 
public class GFG {
 
  // Structure of the linked list
  public class Node {
    public int data;
    public Node next;
  };
 
  static Node head = null;
 
  // Function to create nodes of
  // the linked list
  static void CreateList(int new_data) {
    Node new_node = new Node();
    new_node.data = new_data;
    new_node.next = head;
    head = new_node;
  }
 
  // Function to print the linked list
  static void printList() {
    Node temp;
    temp = head;
 
    // Traversing linked list
    while (temp != null) {
      Console.Write(temp.data + " ");
      temp = temp.next;
    }
  }
 
  // Driver Code
  public static void Main(String[] args) {
    CreateList(1);
    CreateList(2);
    CreateList(3);
    CreateList(4);
    printList();
  }
}
 
// This code is contributed by umadevi9616


Javascript




<script>
// javascript program to implement
// the above approach
 
    // Structure of the linked list
     class Node {
         constructor(){
        this.data = 0;
        this.next = null;
    }
    }
    var head = null;
 
    // Function to create nodes of
    // the linked list
    function CreateLinkedList(new_data)
    {
        var new_node = new Node();
        new_node.data = new_data;
        new_node.next = head;
        head = new_node;
    }
 
    // Function to print the linked list
    function printLinkedList()
    {
        var temp;
        temp = head;
 
        // Traversing linked list
        while (temp != null) {
            document.write(temp.data + " ");
            temp = temp.next;
        }
    }
 
    // Driver Code
        CreateLinkedList(1);
        CreateLinkedList(2);
        CreateLinkedList(3);
        CreateLinkedList(4);
        printLinkedList();
 
// This code is contributed by umadevi9616
</script>


Python3




# Python3 program to implement
# the above approach
 
# Node structure
class Node:
    def __init__(self, data):
        self.data = data
        self.next = None
 
# Head of the linked list
head = None
 
# Function to create nodes
# of the linked list
def CreateLinkedList(new_data):
    global head
     
    # Allocating node and
    # putting data in it
    new_node = Node(new_data)
     
    # Making the new node
    # as head node of linked list
    new_node.next = head
    head = new_node
 
# Function to print the linked list
def printLinkedList():
    temp = head
    while (temp):
        print(temp.data, end = " ")
        temp = temp.next
 
# Driver Code
if __name__ == '__main__':
    CreateLinkedList(1)
    CreateLinkedList(2)
    CreateLinkedList(3)
    CreateLinkedList(4)
    printLinkedList()


Output:

4 3 2 1

Linked list in Stack vs Heap Memory

S No. Linked List in Stack Memory Linked List in Heap Memory
1 Linked list in stack will get access to relatively small memory that is not dynamically expandable. Linked list in heap will get access to dynamically expandable memory.
2 Each node created in the linked list and stored in the stack will get linked deleted after it goes out of scope. There is a need to free the memory for the node to be deleted.
3 If there is a need to store a linked list in the stack area then implement a linked list without using malloc or a new function. If there is a need to store linked list in heap then implement linked list using malloc or new function.
4 Linked list nodes created in the stack cannot be accessed after  the scope of function ends. Linked list nodes created and stored in heap memory can be accessed after the scope of the function ends.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads