💻 Programming

Linked List

Linked List

A data structure in which nodes are connected by pointers. Insertion/deletion O(1), access O(n). Used in LRU caches and undo features.

📖 Detailed Explanation

A linked list is a linear data structure in which nodes that store data are connected to one another through pointers. Each node consists of a data field that holds the actual data and a pointer field that points to the memory address of the next node. Unlike an array, it is not stored contiguously in memory, so its size can be adjusted dynamically.

Linked lists are divided into three main types according to their structure. In a singly linked list, each node points only to the next node, while in a doubly linked list, each node points to both the previous node and the next node. In a circular linked list, the last node points to the first node, forming a circular structure.

The biggest difference between linked lists and arrays lies in time complexity. A linked list can insert/delete at a specific position very quickly in O(1), but random access by index requires traversing from the beginning, so it takes O(n). In contrast, an array has O(1) index access, but inserting/deleting in the middle requires O(n) because elements must be shifted.

In practice, a linked list is used together with a hash map in an LRU (Least Recently Used) cache implementation to add, delete, and reposition cache entries in O(1) time. It is also widely used where sequential traversal and frequent insertion/deletion are needed, such as the undo feature of text editors, the forward/back history of browsers, and the playlists of music players.

📊 Array vs Linked List Time Complexity

Operation Array Linked List Winner
Index access O(1) O(n) Array
Insert at beginning O(n) O(1) Linked List
Insert at end O(1)* O(1)** Equal
Insert in middle O(n) O(1)*** Linked List
Search O(n) O(n) Equal
Memory efficiency Good (contiguous memory) Pointer overhead Array

* Average O(1) for a dynamic array, worst case O(n) (when resizing)
** When a tail pointer exists
*** When a reference to the node at the insertion position is already held

💻 Code Example

# Python 연결 리스트 구현 예제
class Node:
    """연결 리스트의 노드"""
    def __init__(self, data):
        self.data = data      # 데이터 저장
        self.next = None      # 다음 노드 포인터
        self.prev = None      # 이전 노드 포인터 (이중 연결 리스트용)


class LinkedList:
    """단일 연결 리스트 구현"""
    def __init__(self):
        self.head = None
        self.tail = None
        self._size = 0

    def append(self, data):
        """맨 뒤에 노드 추가 - O(1)"""
        new_node = Node(data)
        if not self.head:
            self.head = self.tail = new_node
        else:
            self.tail.next = new_node
            self.tail = new_node
        self._size += 1

    def prepend(self, data):
        """맨 앞에 노드 추가 - O(1)"""
        new_node = Node(data)
        new_node.next = self.head
        self.head = new_node
        if not self.tail:
            self.tail = new_node
        self._size += 1

    def delete(self, data):
        """값으로 노드 삭제 - O(n)"""
        if not self.head:
            return False

        # 헤드 삭제의 경우
        if self.head.data == data:
            self.head = self.head.next
            if not self.head:
                self.tail = None
            self._size -= 1
            return True

        # 중간/끝 노드 삭제
        current = self.head
        while current.next:
            if current.next.data == data:
                if current.next == self.tail:
                    self.tail = current
                current.next = current.next.next
                self._size -= 1
                return True
            current = current.next
        return False

    def find(self, data):
        """값으로 노드 검색 - O(n)"""
        current = self.head
        index = 0
        while current:
            if current.data == data:
                return index
            current = current.next
            index += 1
        return -1

    def __len__(self):
        return self._size

    def __iter__(self):
        current = self.head
        while current:
            yield current.data
            current = current.next

    def __repr__(self):
        return " -> ".join(str(item) for item in self) + " -> None"


# 사용 예제
if __name__ == "__main__":
    ll = LinkedList()
    ll.append(1)
    ll.append(2)
    ll.append(3)
    ll.prepend(0)

    print(f"리스트: {ll}")           # 0 -> 1 -> 2 -> 3 -> None
    print(f"길이: {len(ll)}")         # 4
    print(f"2의 위치: {ll.find(2)}")  # 2

    ll.delete(2)
    print(f"삭제 후: {ll}")           # 0 -> 1 -> 3 -> None

🗣️ Examples of Practical Conversations

In a Technical Interview - Array vs Linked List Time Complexity

"The key difference between arrays and linked lists is memory layout and the resulting time complexity. An array uses contiguous memory, so index access is O(1), but inserting in the middle requires shifting all the following elements, which is O(n). A linked list, on the contrary, only needs pointers to be modified, so insertion/deletion is O(1), but access is O(n) because you have to traverse to the specific position. So I use a linked list where frequent insertion/deletion is needed, like an LRU cache, and an array where there is a lot of random access."

During a Code Review - Discussing Memory Efficiency

"I think we should switch this part from LinkedList to ArrayList. There are 1 million data items, and a linked list needs an extra pointer per node, so the memory overhead is large. On top of that, the nodes are scattered in memory, so the CPU cache hit rate also drops. In this case, access is mostly sequential and there are almost no insertions in the middle, so an array is much more efficient. In terms of cache locality, an array can be more than 10 times faster."

In a System Design Discussion

"If you implement an LRU cache with a combination of a HashMap and a doubly linked list, both get and put can be handled in O(1). The HashMap provides O(1) lookup, and the doubly linked list manages the most recent access order. An accessed item is moved to the front of the list, and when the cache is full, the item at the back is removed. Java's LinkedHashMap works on exactly this principle."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

⚠️ Cautions

1
Memory Fragmentation

The nodes of a linked list are allocated scattered throughout heap memory. As a result, memory fragmentation can occur, and each node requires additional memory for the pointer (8 bytes on a 64-bit system). For storing small amounts of data, it may actually use more memory than an array.

2
Lack of Cache Locality

Modern CPUs load contiguous memory in units of cache lines. In an array, elements are laid out contiguously, so the cache hit rate is high, but in a linked list, nodes are dispersed, so cache misses are frequent. In traversal operations, an array can be dozens of times faster than a linked list.

3
Handling null/None Pointers

When implementing a linked list, NullPointerException frequently occurs in the boundary conditions of an empty list, a single-node list, and head/tail. In insertion/deletion logic, you must always check first for cases where head, tail, or current.next is null. Be sure to cover edge cases with unit tests.

🔗 Related Terms

📚 Learn More