We have discussed the linked list data structure, which is dynamic in nature (the memory is allocated during the run time). Now the question that might be on a few people’s minds is – can a linked link be implemented statically as well? This post tries to answer this question.

The fundamental purpose of a pointer-based linked list is to provide dynamic expansion, but when your linked list does not need to have a dynamic size, we can use static storage for it. The automatic storage has the property that its lifetime ends when the block’s execution is declared terminated, so it is difficult to use it for long-lived data. Also, there’s typically a bound on the amount of such storage we can obtain, and past that memory, the overflow will happen. And there is no way to detect when we have exceeded that bound.

The following code in C, Java, and Python uses automatic storage to allocate nodes of the linked list:

C


Download  Run Code

Output:

1 —> 2 —> 3 —> 4 —> 5 —> NULL

Java


Download  Run Code

Output:

1 —> 2 —> 3 —> 4 —> 5 —> null

Python


Download  Run Code

Output:

1 —> 2 —> 3 —> 4 —> 5 —> None

The above method will become a pain if the total number of nodes required is huge in the linked list. We can construct a linked list easily using iteration if the keys are given in the form of an array or any other data structure (using its iterator).

Following is the C, Java, and Python implementation of the idea:

C


Download  Run Code

Output:

1 —> 2 —> 3 —> 4 —> 5 —> NULL

Java


Download  Run Code

Output:

1 —> 2 —> 3 —> 4 —> 5 —> null

Python


Download  Run Code

Output:

1 —> 2 —> 3 —> 4 —> 5 —> None

These nodes’ lifetime is the scope they are declared in – they no longer exist when the scope ends. We can verify that by placing our code inside the block scope and accessing the nodes outside the block scope.

Following is the C, Java, and Python program that demonstrates it:

C


Download  Run Code

Output:

Runtime Error

Java


Download  Run Code

Output:

1 —> 2 —> 3 —> 4 —> 5 —> null

As discussed, linked list nodes declared in automatic storage won’t hang around after you’ve left the scope in they were defined. The solution is to make it global, as demonstrated below in C, Java, and Python:

C


Download  Run Code

Output:

1 —> 2 —> 3 —> 4 —> 5 —> NULL

Java


Download  Run Code

Output:

1 —> 2 —> 3 —> 4 —> 5 —> null

Python


Download  Run Code

Output:

1 —> 2 —> 3 —> 4 —> 5 —> None