LinkedList 내부 구조 분석: Java에서의 활용

Java의 LinkedList 소스 코드를 깊이 있게 살펴보겠습니다. 이 자료구조는 List와 Deque 인터페이스를 구현하며, 데이터 저장 및 조작에 유용합니다.

LinkedList 개요

LinkedList는 양방향 연결 리스트로 구현된 자료구조입니다. 배열 기반의 ArrayList와 달리, 중간 삽입 및 삭제가 효율적이나 랜덤 접근은 비효율적입니다.

LinkedList 소스 코드 구조 분석

  1. 멤버 변수
  • Node 클래스: 각 노드는 prev, value, next 세 가지 필드를 가집니다. 이를 통해 양방향 탐색이 가능합니다.
private static class Node<T> {
    T value;
    Node<T> next;
    Node<T> prev;
    Node(Node<T> prev, T value, Node<T> next) {
        this.value = value;
        this.next = next;
        this.prev = prev;
    }
}
  • first, last: 각각 첫 번째와 마지막 노드를 가리킵니다.
  1. 생성자
  • 기본 생성자는 빈 LinkedList를 생성합니다.
public LinkedList() {}
  • Collection을 받는 생성자는 주어진 컬렉션의 모든 요소를 LinkedList에 추가합니다.
public LinkedList(Collection<? extends T> c) {
    this();
    addAll(c);
}

핵심 메서드 분석

  1. 추가 작업
  • 리스트 끝에 요소 추가 (add(T e)):
public boolean add(T e) {
    attachLast(e);
    return true;
}
void attachLast(T e) {
    final Node<T> l = last;
    final Node<T> newNode = new Node<>(l, e, null);
    last = newNode;
    if (l == null)
        first = newNode;
    else
        l.next = newNode;
    size++;
}
  • 특정 위치에 요소 추가 (add(int index, T element)):
public void add(int index, T element) {
    if (index == size)
        attachLast(element);
    else if (index == 0)
        attachFirst(element);
    else
        insertBefore(element, locate(index));
}
  1. 삭제 작업
  • 특정 요소 삭제 (remove(Object o)):
public boolean remove(Object o) {
    for (Node<T> x = first; x != null; x = x.next) {
        if (Objects.equals(o, x.value)) {
            detach(x);
            return true;
        }
    }
    return false;
}
T detach(Node<T> x) {
    final T element = x.value;
    final Node<T> next = x.next;
    final Node<T> prev = x.prev;
    if (prev == null) {
        first = next;
    } else {
        prev.next = next;
        x.prev = null;
    }
    if (next == null) {
        last = prev;
    } else {
        next.prev = prev;
        x.next = null;
    }
    x.value = null;
    size--;
    return element;
}
  1. 검색 작업
  • 인덱스로 요소 찾기 (get(int index)):
public T get(int index) {
    return locate(index).value;
}
Node<T> locate(int index) {
    if (index < (size >> 1)) {
        Node<T> x = first;
        for (int i = 0; i < index; i++)
            x = x.next;
        return x;
    } else {
        Node<T> x = last;
        for (int i = size - 1; i > index; i--)
            x = x.prev;
        return x;
    }
}

프론트엔드에서 LinkedList 데이터 표시 (Vue3 + TypeScript)

API로부터 LinkedList 데이터를 받아 Vue3 애플리케이션에 표시할 수 있습니다.

<template>
  <div>
    <h2>LinkedList 데이터</h2>
    - {{ item }}
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';

const listData = ref<any[]>([]);

onMounted(async () => {
  const response = await fetch('your_api_endpoint');
  const data: any[] = await response.json();
  listData.value = data;
});
</script>

Python에서의 간단한 LinkedList 구현

Python에서는 LinkedList를 직접 구현해야 합니다. 다음은 간단한 단방향 LinkedList 예제입니다.

class ListNode:
    def __init__(self, val=0, nxt=None):
        self.val = val
        self.nxt = nxt

class SimpleLinkedList:
    def __init__(self):
        self.head = None

    def append(self, val):
        new_node = ListNode(val)
        if not self.head:
            self.head = new_node
        else:
            current = self.head
            while current.nxt:
                current = current.nxt
            current.nxt = new_node

    def display(self):
        current = self.head
        while current:
            print(current.val, end=' ')
            current = current.nxt
        print()

# 테스트 코드
my_list = SimpleLinkedList()
my_list.append(1)
my_list.append(2)
my_list.append(3)
my_list.display()

태그: java LinkedList Vue.js TypeScript python

7월 22일 02:04에 게시됨