What are the key differences between stack implementation with array and linked list?

Content: Array Vs Linked List

  1. Comparison Chart
  2. Definition
  3. Key Differences
  4. Conclusion

Comparison Chart

Basis for ComparisonArrayLinked list
BasicIt is a consistent set of a fixed number of data items.It is an ordered set comprising a variable number of data items.
SizeSpecified during declaration.No need to specify; grow and shrink during execution.
Storage AllocationElement location is allocated during compile time.Element position is assigned during run time.
Order of the elementsStored consecutivelyStored randomly
Accessing the elementDirect or randomly accessed, i.e., Specify the array index or subscript.Sequentially accessed, i.e., Traverse starting from the first node in the list by the pointer.
Insertion and deletion of elementSlow relatively as shifting is required.Easier, fast and efficient.
SearchingBinary search and linear searchlinear search
Memory requiredlessMore
Memory UtilizationIneffectiveEfficient

Definition of Array

An array is defined as a set of a definite number of homogeneous elements or data items. It means an array can contain one type of data only, either all integers, all floating-point numbers, or all characters. Declaration of an array is as follows:

int a [10];

Where int specifies the data type or type elements array stores. “a” is the name of an array, and the number specified inside the square brackets is the number of elements an array can store, this is also called size or length of the array.

Points to Ponder

Let us look at some of the concepts to be remembered about arrays:

  • The individual elements of an array can be accessed by describing the name of the array, followed by index or subscript [determining the location of the element in the array] inside the square brackets. For example, to retrieve 5th element of the array, we need to write a statement a[4].
  • In any case the elements of an array will be stored in a consecutive memory location.
  • The very first element of the array has index zero [0]. It means the first and last element will be specified as a[0], and a[9] respectively.
  • The number of elements that can be stored in an array, i.e., the size of an array or its length is given by the following equation:
    [upper bound-lower bound] + 1
    For the above array, it would be [9-0] + 1 =10. Where 0 is the lower bound of the array, and 9 is the upper bound of the array.
  • Arrays can be read or written through the loop. If we read the one-dimensional array, it requires one loop for reading and other for writing [printing] the array, for example:
    a. For reading an array
    for [ i= 0; i next = q -> next;
    q -> = p;
    }
    else
    {
    p -> next = start;
    start = p;
    }
    printf ["Do you want to continue [type y or n] ? \n"];
    scanf ["%c", &choice] ;
    }
    while [[choice == 'y'] || [choice == 'Y']];
    }

    Array vs Linked List

    Array and Linked list are the two ways of organizing the data in the memory. Before understanding the differences between the Array and the Linked List, we first look at an array and a linked list.

    What is an array?

    An array is a data structure that contains the elements of the same type. A data structure is a way of organizing the data; an array is a data structure because it sequentially organizes the data. An array is a big chunk of memory in which memory is divided into small-small blocks, and each block is capable of storing some value.

    Suppose we have created an array that consists of 10 values, then each block will store the value of an integer type. If we try to store the value in an array of different types, then it is not a correct array and will throw a compile-time error.

    Declaration of array

    An array can be declared as:

    To declare an array, we first need to specify the type of the array and then the array's name. Inside the square brackets, we need to specify the number of elements that our array should contain.

    Let's understand through an example.

    In the above case, we have declared an array of 5 elements with 'a' name of an integer data type.

    What is Linked list?

    A linked list is the collection of nodes that are randomly stored. Each node consists of two fields, i.e., data and link. Here, data is the value stored at that particular node, and the link is the pointer that holds the address of the next node.

    Differences between Array and Linked list

    We cannot say which data structure is better, i.e., array or linked list. There can be a possibility that one data structure is better for one kind of requirement, while the other data structure is better for another kind of requirement. There are various factors like what are the frequent operations performed on the data structure or the size of the data, and other factors also on which basis the data structure is selected. Now we will see some differences between the array and the linked list based on some parameters.

    1. Cost of accessing an element

    In case of an array, irrespective of the size of an array, an array takes a constant time for accessing an element. In an array, the elements are stored in a contiguous manner, so if we know the base address of the element, then we can easily get the address of any element in an array. We need to perform a simple calculation to obtain the address of any element in an array. So, accessing the element in an array is O[1] in terms of time complexity.

    In the linked list, the elements are not stored in a contiguous manner. It consists of multiple blocks, and each block is represented as a node. Each node has two fields, i.e., one is for the data field, and another one stores the address of the next node. To find any node in the linked list, we first need to determine the first node known as the head node. If we have to find the second node in the list, then we need to traverse from the first node, and in the worst case, to find the last node, we will be traversing all the nodes. The average case for accessing the element is O[n].

    We conclude that the cost of accessing an element in array is less than the linked list. Therefore, if we have any requirement for accessing the elements, then array is a better choice.

    2. Cost of inserting an element

    There can be three scenarios in the insertion:

    • Inserting the element at the beginning: To insert the new element at the beginning, we first need to shift the element towards the right to create a space in the first position. So, the time complexity will be proportional to the size of the list. If n is the size of the array, the time complexity would be O[n].

    In the case of a linked list, to insert an element at the starting of the linked list, we will create a new node, and the address of the first node is added to the new node. In this way, the new node becomes the first node. So, the time complexity is not proportional to the size of the list. The time complexity would be constant, i.e., O[1].

    • Inserting an element at the end

    If the array is not full, then we can directly add the new element through the index. In this case, the time complexity would be constant, i.e., O[1]. If the array is full, we first need to copy the array into another array and add a new element. In this case, the time complexity would be O[n].

    To insert an element at the end of the linked list, we have to traverse the whole list. If the linked list consists of n elements, then the time complexity would be O[n].

    • Inserting an element at the mid

    Suppose we want to insert the element at the ith position of the array; we need to shift the n/2 elements towards the right. Therefore, the time complexity is proportional to the number of the elements. The time complexity would be O[n] for the average case.

    In the case of linked list, we have to traverse to that position where we have to insert the new element. Even though, we do not have to perform any kind of shifting, but we have to traverse to n/2 position. The time taken is proportional to the n number of elements, and the time complexity for the average case would be O[n].

    The resultant linked list is:

    • Ease of use

    The implementation of an array is easy as compared to the linked list. While creating a program using a linked list, the program is more prone to errors like segmentation fault or memory leak. So, lots of care need to be taken while creating a program in the linked list.

    • Dynamic in size

    The linked list is dynamic in size whereas the array is static. Here, static doesn't mean that we cannot decide the size at the run time, but we cannot change it once the size is decided.

    3. Memory requirements

    As the elements in an array store in one contiguous block of memory, so array is of fixed size. Suppose we have an array of size 7, and the array consists of 4 elements then the rest of the space is unused. The memory occupied by the 7 elements:

    Memory space = 7*4 = 28 bytes

    Where 7 is the number of elements in an array and 4 is the number of bytes of an integer type.

    In case of linked list, there is no unused memory but the extra memory is occupied by the pointer variables. If the data is of integer type, then total memory occupied by one node is 8 bytes, i.e., 4 bytes for data and 4 bytes for pointer variable. If the linked list consists of 4 elements, then the memory space occupied by the linked list would be:

    Memory space = 8*4 = 32 bytes

    The linked list would be a better choice if the data part is larger in size. Suppose the data is of 16 bytes. The memory space occupied by the array would be 16*7=112 bytes while the linked list occupies 20*4=80, here we have specified 20 bytes as 16 bytes for the size of the data plus 4 bytes for the pointer variable. If we are choosing the larger size of data, then the linked list would consume a less memory; otherwise, it depends on the factors that we are adopting to determine the size.

    Let's look at the differences between the array and linked list in a tabular form.

    ArrayLinked list
    An array is a collection of elements of a similar data type.A linked list is a collection of objects known as a node where node consists of two parts, i.e., data and address.
    Array elements store in a contiguous memory location.Linked list elements can be stored anywhere in the memory or randomly stored.
    Array works with a static memory. Here static memory means that the memory size is fixed and cannot be changed at the run time.The Linked list works with dynamic memory. Here, dynamic memory means that the memory size can be changed at the run time according to our requirements.
    Array elements are independent of each other.Linked list elements are dependent on each other. As each node contains the address of the next node so to access the next node, we need to access its previous node.
    Array takes more time while performing any operation like insertion, deletion, etc.Linked list takes less time while performing any operation like insertion, deletion, etc.
    Accessing any element in an array is faster as the element in an array can be directly accessed through the index.Accessing an element in a linked list is slower as it starts traversing from the first element of the linked list.
    In the case of an array, memory is allocated at compile-time.In the case of a linked list, memory is allocated at run time.
    Memory utilization is inefficient in the array. For example, if the size of the array is 6, and array consists of 3 elements only then the rest of the space will be unused.Memory utilization is efficient in the case of a linked list as the memory can be allocated or deallocated at the run time according to our requirement.

    Next TopicStack vs. Queue



    ← prev next →



    Understanding the Difference Between Array and Linked List

    Lesson 49 of 54By Nikita Duggal

    Last updated on Dec 14, 20214696

    PreviousNext

    • Tutorial Playlist

      Data Structure Tutorial

      Overview

      Arrays in Data Structures: A Guide With Examples

      Lesson - 1

      All You Need to Know About Two-Dimensional Arrays

      Lesson - 2

      All You Need to Know About a Linked List in a Data Structure

      Lesson - 3

      The Complete Guide to Implement a Singly Linked List

      Lesson - 4

      The Ultimate Guide to Implement a Doubly Linked List

      Lesson - 5

      The Fundamentals for Understanding Circular Linked List

      Lesson - 6

      The Ultimate Guide To Understand The Differences Between Stack And Queue

      Lesson - 7

      Implementing Stacks in Data Structures

      Lesson - 8

      Your One-Stop Solution for Stack Implementation Using Array

      Lesson - 9

      Your One-Stop Solution for Queue Implementation Using Array

      Lesson - 10

      Your One-Stop Solution to Learn Depth-First Search[DFS] Algorithm From Scratch

      Lesson - 11

      Your One-Stop Solution for Stack Implementation Using Linked-List

      Lesson - 12

      The Definitive Guide to Understand Stack vs Heap Memory Allocation

      Lesson - 13

      All You Need to Know About Linear Search Algorithm

      Lesson - 14

      All You Need to Know About Breadth-First Search Algorithm

      Lesson - 15

      A One-Stop Solution for Using Binary Search Trees in Data Structure

      Lesson - 16

      The Best Tutorial to Understand Trees in Data Structure

      Lesson - 17

      A Complete Guide to Implement Binary Tree in Data Structure

      Lesson - 18

      A Holistic Look at Using AVL Trees in Data Structures

      Lesson - 19

      All You Need to Know About Tree Traversal in Data Structure

      Lesson - 20

      The Best Guide You’ll Ever Need to Understand B-Tree in Data Structure

      Lesson - 21

      The Best Guide You'll Ever Need to Understand Spanning Tree in Data Structure

      Lesson - 22

      The Best and Easiest Way to Understand an Algorithm

      Lesson - 23

      Your One-Stop Solution to Understand Shell Sort Algorithm

      Lesson - 24

      Your One-Stop Solution to Quick Sort Algorithm

      Lesson - 25

      The Most Useful Guide to Learn Selection Sort Algorithm

      Lesson - 26

      Everything You Need to Know About Radix Sort Algorithm

      Lesson - 27

      Everything You Need to Know About the Counting Sort Algorithm

      Lesson - 28

      Everything You Need to Know About the Merge Sort Algorithm

      Lesson - 29

      Insertion Sort Algorithm: One-Stop Solution That Will Help You Understand Insertion Sort

      Lesson - 30

      Everything You Need to Know About the Bubble Sort Algorithm

      Lesson - 31

      The Best Guide You’ll Ever Need to Understand Bucket Sort Algorithm

      Lesson - 32

      Your One-Stop Solution to Understand Recursive Algorithm in Programming

      Lesson - 33

      The Definitive Guide to Understanding Greedy Algorithm

      Lesson - 34

      Your One-Stop Solution to Understand Backtracking Algorithm

      Lesson - 35

      The Fundamentals of the Bellman-Ford Algorithm

      Lesson - 36

      Your One-Stop Solution for Graphs in Data Structures

      Lesson - 37

      The Best Guide to Understand and Implement Solutions for Tower of Hanoi Puzzle

      Lesson - 38

      A Simplified and Complete Guide to Learn Space and Time Complexity

      Lesson - 39

      All You Need to Know About the Knapsack Problem : Your Complete Guide

      Lesson - 40

      The Fibonacci Series: Mathematical and Programming Interpretation

      Lesson - 41

      The Holistic Look at Longest Common Subsequence Problem

      Lesson - 42

      The Best Article to Understand What Is Dynamic Programming

      Lesson - 43

      A Guide to Implement Longest Increasing Subsequence Using Dynamic Programming

      Lesson - 44

      A Holistic Guide to Learn Stop Solution Using Dynamic Programming

      Lesson - 45

      One Stop Solution to All the Dynamic Programming Problems

      Lesson - 46

      Understanding the Fundamentals of Binomial Distribution

      Lesson - 47

      Here’s All You Need to Know About Minimum Spanning Tree in Data Structures

      Lesson - 48

      Understanding the Difference Between Array and Linked List

      Lesson - 49

      The Best Article Out There to Understand the B+ Tree in Data Structure

      Lesson - 50

      A Comprehensive Look at Queue in Data Structure

      Lesson - 51

      Your One-Stop Solution to Understand Coin Change Problem

      Lesson - 52

      The Best Way to Understand the Matrix Chain Multiplication Problem

      Lesson - 53

      Your One-Stop Solution to Learn Floyd-Warshall Algorithm for Using Dynamic Programming

      Lesson - 54

    Table of Contents

    View More

    Data structures are formats implemented in computer programming to store, manage, and organize data items. These storage formats enable efficient access and modification of data elements. There are several data structures for organizing data in memory, but perhaps the most basic ones are array and linked list. Both these data structures store homogeneous elements in sequential order. However, there are a lot of differences between arrays and linked lists. So, in this tutorial, we will unleash a few key differences between these data structures.

    Post Graduate Program: Full Stack Web Development

    in Collaboration with Caltech CTMEEnroll Now

    Difference between Array and Linked List

    Both Linked List and Array are used to store linear data of similar type, but an array consumes contiguous memory locations allocated at compile time, i.e. at the time of declaration of array, while for a linked list, memory is assigned as and when data is added to it, which means at runtime.

    Before we proceed further with the differences between Array and Linked List, if you are not familiar with Array or Linked list or both, you can check these topics first:

    • Array in C
    • Linked List

    This is the basic and the most important difference between a linked list and an array. In the section below, we will discuss this in details along with highlighting other differences.

    Where is Stack used ?

    • Usually, most of the recusrsive programs use stack implementation internally to follow recursion and when a programmer wants to convert the recusrive function to an iterative function stack data structure can be used to achieve this very easily.

    • Expression conversion and evaluation like converting an infix expression to postfix, prefix and vice versa or to check if the paranthesis in an expression are balanced or not and evaluation of expressions can be programmed easily using a dtack.

    • Stack is used to implement algorihtms like tower of hanoi and other graph algorithms.

    Linked List vs Array

    Arrays store elements in contiguous memory locations, resulting in easily calculable addresses for the elements stored and this allows faster access to an element at a specific index. Linked lists are less rigid in their storage structure and elements are usually not stored in contiguous locations, hence they need to be stored with additional tagsgiving a reference to the next element. This difference in the data storage scheme decides which data structure would be more suitable for a given situation.

    Data storage scheme of an array

    Data storage scheme of a linked list

    Major differences are listed below:

    • Size: Since data can only be stored in contiguous blocks of memory in an array, its size cannot be altered at runtime due to the risk of overwriting other data. However, in a linked list, each node points to the next one such that data can exist at scattered [non-contiguous] addresses; this allows for a dynamic size that can change at runtime.
    • Memory allocation: For arrays at compile time and at runtime for linked lists. but, a dynamically allocated array also allocates memory at runtime.
    • Memory efficiency: For the same number of elements, linked lists use more memory as a reference to the next node is also stored along with the data. However, size flexibility in linked lists may make them use less memory overall; this is useful when there is uncertainty about size or there are large variations in the size of data elements; memory equivalent to the upper limit on the size has to be allocated [even if not all of it is being used] while using arrays, whereas linked lists can increase their sizes step-by-step proportionately to the amount of data.
    • Execution time: Any element in an array can be directly accessed with its index; however in the case of a linked list, all the previous elements must be traversed to reach any element. Also, better cache locality in arrays [due to contiguous memory allocation] can significantly improve performance. As a result, some operations [such as modifying a certain element] are faster in arrays, while some others [such as inserting/deleting an element in the data] are faster in linked lists.

    Following are the points in favor of Linked Lists.
    [1] The size of the arrays is fixed: So we must know the upper limit on the number of elements in advance. Also, generally, the allocated memory is equal to the upper limit irrespective of the usage, and in practical uses, the upper limit is rarely reached.



    [2] Inserting a new element in an array of elements is expensive because room has to be created for the new elements and to create room existing elements have to be shifted.

    For example, suppose we maintain a sorted list of IDs in an array id[ ].

    id[ ] = [1000, 1010, 1050, 2000, 2040, …..].

    And if we want to insert a new ID 1005, then to maintain the sorted order, we have to move all the elements after 1000 [excluding 1000].

    Deletion is also expensive with arrays unless some special techniques are used. For example, to delete 1010 in id[], everything after 1010 has to be moved.

    So Linked list provides the following two advantages over arrays
    1] Dynamic size
    2] Ease of insertion/deletion

    Linked lists have the following drawbacks:
    1] Random access is not allowed. We have to access elements sequentially starting from the first node. So we cannot do a binary search with linked lists.
    2] Extra memory space for a pointer is required with each element of the list.
    3] Arrays have better cache locality that can make a pretty big difference in performance.

    4] It takes a lot of time in traversing and changing the pointers.

    5] It will be confusing when we work with pointers.

    References:
    //cslibrary.stanford.edu/103/LinkedListBasics.pdf

    Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

    Article Tags :

    Arrays

    Linked List

    Practice Tags :

    Linked List

    Arrays

    Read Full Article

    Implement a stack using singly linked list

    To implement a stack using singly linked list concept , all the singly linked list operations are performed based on Stack operations LIFO[last in first out] and with the help of that knowledge we are going to implement a stack using single linked list. Using singly linked lists , we implement stack by storing the information in the form of nodes and we need to follow the stack rules and implement using singly linked list nodes . So we need to follow a simple rule in the implementation of a stack which is last in first out and all the operations can be performed with the help of a top variable .Let us learn how to perform Pop , Push , Peek ,Display operations in the following article .

    A stack can be easily implemented using the linked list. In stack Implementation, a stack contains a top pointer. which is “head” of the stack where pushing and popping items happens at the head of the list. First node have null in link field and second node link have first node address in link field and so on and last node address in “top” pointer.
    The main advantage of using linked list over an arrays is that it is possible to implement a stack that can shrink or grow as much as needed. In using array will put a restriction to the maximum capacity of the array which can lead to stack overflow. Here each new node will be dynamically allocate. so overflow is not possible.
    Stack Operations:

    1. push[] : Insert a new element into stack i.e just inserting a new element at the beginning of the linked list.
    2. pop[] : Return top element of the Stack i.e simply deleting the first element from the linked list.
    3. peek[]: Return the top element.
    4. display[]: Print all elements in Stack.

    Below is the implementation of the above approach:

    C++




    // C++ program to Implement a stack

    //using singly linked list

    #include

    using namespace std;

    // Declare linked list node

    struct Node

    {

    int data;

    Node* link;

    };

    Node* top;

    // Utility function to add an element

    // data in the stack insert at the beginning

    void push[int data]

    {

    // Create new node temp and allocate memory in heap

    Node* temp = new Node[];

    // Check if stack [heap] is full.

    // Then inserting an element would

    // lead to stack overflow

    if [!temp]

    {

    cout data = data;

    // Put top pointer reference into temp link

    temp->link = top;

    // Make temp as top of Stack

    top = temp;

    }

    // Utility function to check if

    // the stack is empty or not

    int isEmpty[]

    {

    //If top is NULL it means that

    //there are no elements are in stack

    return top == NULL;

    }

    // Utility function to return top element in a stack

    int peek[]

    {

    // If stack is not empty , return the top element

    if [!isEmpty[]]

    return top->data;

    else

    exit[1];

    }

    // Utility function to pop top

    // element from the stack

    void pop[]

    {

    Node* temp;

    // Check for stack underflow

    if [top == NULL]

    {

    cout 33->22->11-> Top element is 44 22->11-> Top element is 22

    Time Complexity:

    The time complexity for all push[], pop[], and peek[] operations is O[1] as we are not performing any kind of traversal over the list. We perform all the operations through the current pointer only.




    Article Tags :

    Linked List

    Stack

    Technical Scripter

    Technical Scripter 2018

    Practice Tags :

    Linked List

    Stack

    Read Full Article

    Video liên quan

    Bài mới nhất

    Chủ Đề