호빵의 IT 개발소

List에서 index를 구현 본문

자료구조와 알고리즘/자료구조와 알고리즘 맛보기

List에서 index를 구현

호빵Stack 2025. 3. 25. 22:03

List에서 at(index)를 구현한다면 연결 리스트 기준으로:

목표:

at(index)는 해당 인덱스에 있는 노드의 데이터를 반환하는 함수

구현 로직 (단일 연결 리스트 기준):

T at(int index) {
    Node* curr = head;
    int i = 0;

    while (curr != nullptr && i < index) {
        curr = curr->next;
        i++;
    }

    if (curr == nullptr) throw std::out_of_range("Index out of range");

    return curr->data;
}

 

주의점

  • 0 ≤ index < size 체크 필요
  • 연결 리스트는 순차 접근이므로 O(n) 시간 복잡도

 

요약: at(index)는 head부터 차례로 이동하면서 index 번째 노드를 찾아 반환하는 방식으로 구현함.

Comments