Why Linked List is implemented on Heap memory rather than Stack memory?
Last Updated :
05 Mar, 2023
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++
#include <iostream>
using namespace std;
struct Node {
int data;
struct Node* next;
Node( int x)
{
data = x;
next = NULL;
}
}* head = NULL;
void printLinkedList(Node* head)
{
struct Node* temp = head;
while (temp) {
cout << temp->data << " " ;
temp = temp->next;
}
}
int main()
{
struct Node first = Node(1);
struct Node second = Node(2);
struct Node third = Node(3);
struct Node fourth = Node(4);
head = &first;
first.next = &second;
second.next = &third;
third.next = &fourth;
fourth.next = NULL;
printLinkedList(head);
return 0;
}
|
Java
import java.util.*;
class GFG{
static class Node {
int data;
Node next;
Node( int x)
{
data = x;
next = null ;
}
};
static Node head = null ;
static void printLinkedList(Node head)
{
Node temp = head;
while (temp!= null ) {
System.out.print(temp.data+ " " );
temp = temp.next;
}
}
public static void main(String[] args)
{
Node first = new Node( 1 );
Node second = new Node( 2 );
Node third = new Node( 3 );
Node fourth = new Node( 4 );
head = first;
first.next = second;
second.next = third;
third.next = fourth;
fourth.next = null ;
printLinkedList(head);
}
}
|
Python3
class Node:
def __init__( self , x):
self .data = x
self . next = None
head = None
def printLinkedList(head):
temp = head
while temp:
print (temp.data, end = " " )
temp = temp. next
if __name__ = = '__main__' :
first = Node( 1 )
second = Node( 2 )
third = Node( 3 )
fourth = Node( 4 )
head = first
first. next = second
second. next = third
third. next = fourth
fourth. next = None
printLinkedList(head)
|
C#
using System;
using System.Collections.Generic;
public class GFG{
class Node {
public int data;
public Node next;
public Node( int x)
{
data = x;
next = null ;
}
};
static Node head = null ;
static void printList(Node head)
{
Node temp = head;
while (temp!= null ) {
Console.Write(temp.data+ " " );
temp = temp.next;
}
}
public static void Main(String[] args)
{
Node first = new Node(1);
Node second = new Node(2);
Node third = new Node(3);
Node fourth = new Node(4);
head = first;
first.next = second;
second.next = third;
third.next = fourth;
fourth.next = null ;
printList(head);
}
}
|
Javascript
<script>
class Node {
constructor(x) {
this .data = x;
this .next = null ;
}
}
function printLinkedList(head) {
let temp = head;
while (temp) {
document.write(temp.data + " " );
temp = temp.next;
}
}
let first = new Node(1);
let second = new Node(2);
let third = new Node(3);
let fourth = new Node(4);
head = first;
first.next = second;
second.next = third;
third.next = fourth;
fourth.next = null ;
printLinkedList(head);
</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++
#include <iostream>
using namespace std;
struct Node {
int data;
struct Node* next;
Node( int x)
{
data = x;
next = NULL;
}
}* head = NULL;
Node* CreateLinkedList()
{
struct Node first = Node(1);
struct Node second = Node(2);
struct Node third = Node(3);
struct Node fourth = Node(4);
head = &first;
first.next = &second;
second.next = &third;
third.next = &fourth;
fourth.next = NULL;
return head;
}
void printLinkedList(Node* head)
{
struct Node* temp = head;
while (temp) {
cout << temp->data << " " ;
temp = temp->next;
}
}
int main()
{
struct Node* head = CreateLinkedList();
printLinkedList(head);
return 0;
}
|
Java
import java.util.*;
class GFG{
static class Node {
int data;
Node next;
Node( int x)
{
data = x;
next = null ;
}
}
static Node head = null ;
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;
first.next = second;
second.next = third;
third.next = fourth;
fourth.next = null ;
return head;
}
static void printLinkedList(Node head)
{
Node temp = head;
while (temp!= null ) {
System.out.print(temp.data+ " " );
temp = temp.next;
}
}
public static void main(String[] args)
{
Node head = CreateLinkedList();
printLinkedList(head);
}
}
|
C#
using System;
public class GFG{
class Node {
public int data;
public Node next;
public Node( int x)
{
data = x;
next = null ;
}
}
static Node head = null ;
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;
first.next = second;
second.next = third;
third.next = fourth;
fourth.next = null ;
return head;
}
static void printList(Node head)
{
Node temp = head;
while (temp != null ) {
Console.Write(temp.data + " " );
temp = temp.next;
}
}
public static void Main(String[] args)
{
Node head = CreateList();
printList(head);
}
}
|
Javascript
<script>
class Node
{
constructor( x) {
this .data = x;
this .next = null ;
}
}
var head = null ;
function CreateLinkedList() {
var first = new Node(1);
var second = new Node(2);
var third = new Node(3);
var fourth = new Node(4);
head = first;
first.next = second;
second.next = third;
third.next = fourth;
fourth.next = null ;
return head;
}
function printLinkedList( head) {
var temp = head;
while (temp != null ) {
document.write(temp.data + " " );
temp = temp.next;
}
}
var head = CreateLinkedList();
printLinkedList(head);
</script>
|
Python3
class Node:
def __init__( self , x):
self .data = x
self . next = None
head = None
def createLinkedList():
first = Node( 1 )
second = Node( 2 )
third = Node( 3 )
fourth = Node( 4 )
global head
head = first
first. next = second
second. next = third
third. next = fourth
fourth. next = None
return head
def printLinkedList(head):
temp = head
while (temp ! = None ):
print (temp.data, end = " " )
temp = temp. next
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++
#include <iostream>
using namespace std;
struct Node {
int data;
struct Node* next;
};
struct Node* head = NULL;
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;
}
void printLinkedList()
{
struct Node* temp;
temp = head;
while (temp != NULL) {
cout << temp->data << " " ;
temp = temp->next;
}
}
int main()
{
CreateLinkedList(1);
CreateLinkedList(2);
CreateLinkedList(3);
CreateLinkedList(4);
printLinkedList();
return 0;
}
|
Java
import java.util.*;
public class GFG{
static class Node {
int data;
Node next;
};
static Node head = null ;
static void CreateLinkedList( int new_data)
{
Node new_node = new Node();
new_node.data = new_data;
new_node.next = head;
head = new_node;
}
static void printLinkedList()
{
Node temp;
temp = head;
while (temp != null ) {
System.out.print(temp.data+ " " );
temp = temp.next;
}
}
public static void main(String[] args)
{
CreateLinkedList( 1 );
CreateLinkedList( 2 );
CreateLinkedList( 3 );
CreateLinkedList( 4 );
printLinkedList();
}
}
|
C#
using System;
using System.Collections.Generic;
public class GFG {
public class Node {
public int data;
public Node next;
};
static Node head = null ;
static void CreateList( int new_data) {
Node new_node = new Node();
new_node.data = new_data;
new_node.next = head;
head = new_node;
}
static void printList() {
Node temp;
temp = head;
while (temp != null ) {
Console.Write(temp.data + " " );
temp = temp.next;
}
}
public static void Main(String[] args) {
CreateList(1);
CreateList(2);
CreateList(3);
CreateList(4);
printList();
}
}
|
Javascript
<script>
class Node {
constructor(){
this .data = 0;
this .next = null ;
}
}
var head = null ;
function CreateLinkedList(new_data)
{
var new_node = new Node();
new_node.data = new_data;
new_node.next = head;
head = new_node;
}
function printLinkedList()
{
var temp;
temp = head;
while (temp != null ) {
document.write(temp.data + " " );
temp = temp.next;
}
}
CreateLinkedList(1);
CreateLinkedList(2);
CreateLinkedList(3);
CreateLinkedList(4);
printLinkedList();
</script>
|
Python3
class Node:
def __init__( self , data):
self .data = data
self . next = None
head = None
def CreateLinkedList(new_data):
global head
new_node = Node(new_data)
new_node. next = head
head = new_node
def printLinkedList():
temp = head
while (temp):
print (temp.data, end = " " )
temp = temp. next
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
Please Login to comment...