Part 1 - Understanding Linked List

Definition of Linked List

A Linked List is a linear data structure consisting of elements called nodes. Each node has two main parts:

Differences Between Linked List and Array

Aspect Array Linked List
Storage Elements are stored contiguously in memory. Nodes are stored in non-contiguous memory and linked by pointers.
Element Access Direct access using an index, complexity O(1). Access requires traversal from the start, complexity O(n).
Size Static, size determined at declaration. Dynamic, can grow or shrink as needed.
Insert/Delete Expensive due to element shifting, complexity O(n). More efficient, only pointer adjustments needed, complexity O(1) if position is known.

Benefits of Linked List

Dynamic Size

Efficiency in Insert/Delete Operations

More Flexible Memory Usage

Support for Complex Data Structures

Two-Way Traversal (in Doubly Linked List)

Dynamic Memory Allocation

Undo/Redo Operations in Text Editors

Graph Representation

Implementation of Other Data Structures

Advantages of Linked List

Disadvantages of Linked List

Short Code Example

#include <iostream>
using namespace std;

struct Node {
    int data;
    Node* next;
};

void pushFront(Node*& head, int value) {
    Node* newNode = new Node(); // Buat node baru
    newNode->data = value;      // Isi data
    newNode->next = head;       // Hubungkan ke head lama
    head = newNode;             // Jadikan node baru sebagai head
}

void printList(Node* head) {
    Node* current = head;
    while (current != nullptr) {
        cout << current->data << " -> ";
        current = current->next;
    }
    cout << "NULL\n";
}

int main() {
    Node* head = nullptr;  // List kosong

    pushFront(head, 10);
    pushFront(head, 20);
    pushFront(head, 30);

    printList(head); // Output: 30 -> 20 -> 10 -> NULL

    return 0;
}

Code Explanation:


Revision #8
Created 2025-09-02 08:25:22 UTC by BH
Updated 2025-09-04 00:54:44 UTC by BH