1. Home
Data Structure

Data Structure Tutorial: Everything You Need to Know

Learn all about data structures with our comprehensive tutorial. Master the fundamentals and advance your skills in organizing and managing data efficiently.

  • 60
  • 14
right-top-arrow

Tutorial Playlist

58 Lessons
3

Array vs Linked Lists in Data Structure

Updated on 24/07/2024441 Views

When learning about data structures, two fundamental concepts often stand out, which are arrays and linked lists. They serve as the fundamental building blocks in computer science, yet they differ significantly in their implementations and use cases. In this article, we'll explore array vs linked list in data structure, their advantages and disadvantages, and scenarios where one might be preferred over the other.

Overview

Arrays and linked lists represent different approaches to organizing and storing data. An array is a collection of elements stored at contiguous memory locations, identified by an index. On the other hand, a linked list is a linear data structure where elements are stored in nodes, with each node containing a reference to the next node in the sequence.

An array: What is it? How is It Used?

A data structure with members of the same kind is called an array. An array is a data structure because it arranges the data in a sequential manner, which is a method of data organization. An array is a large block of memory that has been split into smaller and smaller blocks, each of which can hold a single value.

Assuming we have an array with ten entries, the values of an integer type will be stored in each block. A compile-time error will occur if we attempt to save the value in an array that has multiple kinds.

Declaring an Array

You can declare an array as:

data_type name of the array[no of elements]   

To declare an array, we first need to specify the type of array along with its name. Afterward, we need to specify the number of elements that our array should contain inside the square brackets.

Array Declaration Example:

In many programming languages, declaring an array involves specifying the type of elements it will contain and its size. Let's illustrate this with an example in the C programming language:

#include <stdio.h>

int main() {

    // Declare an array of integers with a fixed size of 5

    int numbers[5];

 // Assign values to the array elements

    numbers[0] = 10;

    numbers[1] = 20;

    numbers[2] = 30;

    numbers[3] = 40;

    numbers[4] = 50;

// Print the elements of the array

    printf("Elements of the array: ");

    for (int i = 0; i < 5; i++) {

        printf("%d ", numbers[i]);

    }

return 0;

}

In this example, we first declare an array called numbers of type int with a fixed size of 5. 

We then assign values to each element of the array using the index notation (numbers[0], numbers[1], etc.). 

Finally, using a loop, we print out the elements of the array.

What is a Linked List?

A collection of randomly stored nodes is called a linked list. Data and link are the two fields that make up each node. In this case, the value stored at that specific node is called data, and the pointer with the location of the next node is called the link.

Each of the elements in a linked list is dynamically allocated and points to the next element, making it a linear and non-primitive data structure. Put differently, it can be described as a data structure made up of several nodes that concurrently represent a sequence.

Declaring a Linked List

To declare a linked list, we first need to define a structure that represents a node in the list. Each node contains the data and a pointer to the next node in the sequence. Let's illustrate this with an example in the C programming language:

#include <stdio.h>

#include <stdlib.h>

// Define the structure for a node in the linked list

struct Node {

    int data;

    struct Node* next;

};

// Function to insert a new node at the beginning of the linked list

struct Node* insertNode(struct Node* head, int newData) {

    // Create a new node

    struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));

    newNode->data = newData;

    newNode->next = head; // Point the new node to the current head of the list

    return newNode; // Return the new node as the new head of the list

}

// Function to print the elements of the linked list

void printList(struct Node* head) {

    struct Node* temp = head;

    printf("Linked List: ");

    while (temp != NULL) {

        printf("%d ", temp->data);

        temp = temp->next;

    }

    printf("\n");

}

int main() {

    // Initialize an empty linked list

    struct Node* head = NULL;

// Insert elements into the linked list

    head = insertNode(head, 10);

    head = insertNode(head, 20);

    head = insertNode(head, 30);

    head = insertNode(head, 40);

// Print the elements of the linked list

    printList(head);

return 0;

}

The code defines a singly linked list structure, inserts elements at the beginning of the list, and prints the list.

The Difference Between Array and Linked List in Data Structure

It is impossible to determine which data structure—an array or a linked list—is superior. Certain requirements may be better served by a particular data structure while other requirements are better served by a different one. Numerous considerations come into play, such as the amount of data and the types of operations that are frequently done on the data structure. Other aspects also play a role in the selection of data structure. We will now examine array vs linked list in data structure. We will also see some of the variations, depending on a few parameters, between the linked list and the array.

1. The Cost of Insertion

Three possible outcomes exist for the insertion:

  • Insertion at the start

In order to add a new element at the beginning, we must first move the existing element to the right to make room in the initial location. As a result, the time complexity will increase with list size. O(n) would be the time complexity if n is the array's size.

When dealing with a linked list, we first build a new node and add the address of the first node, to insert an element at the beginning of the linked list. Now, the new node takes the place of the original node. Therefore, there is no relationship between the time complexity and list size. There would be a constant time complexity, or O(1).

  • Insertion at the end

We can add a new entry to the array by directly using the index if it has space. The time complexity in this scenario would be O(1) or constant. The array must first be copied into another array and a new element should be added if it is already full. The temporal complexity in this scenario would be O(n).

We must iterate through the entire linked list to add a member at the end. The temporal complexity would be O(n) if the linked list had n elements.

  • Adding an element in the middle

Assume that we need to move the n/2 items to the right, to insert the element at the ith position of the array. As a result, the number of pieces and the temporal complexity are proportionate. In an average instance, the time complexity would be O(n).

When dealing with linked lists, we must traverse to the location where the new element needs to be inserted. Despite not needing to shift in any way, we still need to traverse to the n/2 position. The time complexity for the average situation would be O(n), with the time taken being proportionate to the n number of items.

2. Usability

Compared to a linked list, an array is simpler to implement. When developing a program using a linked list, there is an increased risk of mistakes such as memory leaks and segmentation faults. Thus, much caution must be used when developing a program in the linked list.

3. Dynamic in Dimensions

The array is static, while the size of the linked list is dynamic. Static in this context refers to the inability to modify the size once it has been determined, not the inability to decide at runtime.

4. Memory Needs

An array has a fixed size since its items are stored in a single, continuous block of memory. Assume we have a 7-element array, of which 4 are used and the remaining space is unoccupied. The memory that the seven components took up:

where 4 is the number of bytes of an integer type and 7 is the number of entries in an array.

When dealing with a linked list, pointer variables occupy the unused memory. The total memory usage of the node, if the data is of the integer type, is 8 bytes. It can also be 4 bytes for the data and 4 bytes for the pointer variable. The linked list would take up the following amount of memory if it had four elements:

Memory space = 8*4 = 32 bytes

If the data portion is higher in size, the linked list would be a preferable option. Assume the 16-byte data set. The linked list takes up 20*4=80 bytes of memory, but the array uses 16*7=112 bytes. In this case, the 20 bytes are made up of 16 bytes for the data size and 4 bytes for the pointer variable. The linked list would use less memory if we were to choose a higher data size. Otherwise, it would rely on the parameters we use to decide on size.

Array vs Linked List

Now, let's compare arrays and linked lists across various dimensions to understand their relative strengths and weaknesses.

Feature

Array

Linked List

Access Time

Constant time (O(1))

Linear time (O(n))

Memory Allocation

Contiguous memory

Dynamic memory allocation

Size

Fixed size

Dynamic size

Insertion/Deletion

Inefficient, especially in the middle

Efficient, especially in the middle

Memory Overhead

Minimal

Additional pointers

Flexibility

Limited flexibility due to fixed size

High flexibility due to dynamic memory allocation

Conclusion

Arrays and linked lists are fundamental data structures with distinct characteristics and use cases. Arrays excel in scenarios requiring fast random access and a fixed size, whereas, linked lists shine in situations where dynamic memory allocation and efficient insertions and deletions are paramount. Understanding the differences between these two data structures is essential for making informed design decisions to develop algorithms and applications. Whether you choose an array or a linked list depends on the specific requirements of your problem and the trade-offs you're willing to make.

Frequently Asked Questions:

  1. Difference between Linked List and Array of Structs:
  • A linked list consists of nodes where each node contains a data field and a pointer to the next node in the sequence.
  • An array of structs is an array where each element is a struct, allowing for the storage of multiple fields per element but with fixed size and contiguous memory allocation, unlike the dynamic nature of linked lists.
  1. What is the difference between a Linked List and a Sorted Array:
  • In a linked list, elements are arranged in a linear sequence, connected via pointers, offering dynamic memory allocation and efficient insertion/deletion but slower access time.
  • A sorted array maintains elements in sorted order within the array, enabling faster search operations due to binary search but less efficient insertion/deletion operations compared to a linked list.
  1. Array vs Linked List, which is more efficient?

The comparison between their efficiency varies based on operations. Arrays offer constant-time access but are less efficient for dynamic resizing and insertion/deletion. Linked lists excel in dynamic resizing and insertion/deletion but have slower access time. The choice depends on requirements: arrays for frequent random access with known size, linked lists for dynamic resizing and efficient insertion/deletion.

  1. What are the advantages of using an array over a linked list, and vice versa?
  • Arrays offer constant-time access based on indices and require less memory overhead than linked lists. However, Linked lists provide dynamic memory allocation, efficient insertion/deletion, and flexibility in size but have slower access time due to sequential traversal.
Kechit Goyal

Kechit Goyal

Team Player and a Leader with a demonstrated history of working in startups. Strong engineering professional with a Bachelor of Technology (BTech…Read More

Get Free Career Counselling
form image
+91
*
By clicking, I accept theT&Cand
Privacy Policy
image
right-top-arrowleft-top-arrow

upGrad Learner Support

Talk to our experts. We’re available 24/7.

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918045604032

Disclaimer

upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...