Singly Linked List - head, next, append()

woongaaaa·2024년 4월 6일
0

자료구조

목록 보기
1/5

1번문제 ADT

list.h :

#ifndef ASSIGNMENT_LIST_H
#define ASSIGNMENT_LIST_H

class Node{
private:
    int data;
    Node *next;
    friend class LinkedList;
};

class LinkedList {
public:
    LinkedList() {
        head = nullptr;
    }
    void append(int data);
    int length();
    void print();

private:
    Node *head;

};

#endif //ASSIGNMENT_LIST_H

list.cpp :

#include "list.h"
#include "iostream"

void LinkedList::append(int data) {
    Node *newNode = new Node();
    newNode->data = data;
    newNode->next = nullptr;
    if(head == nullptr){
        head = newNode;
    }else {
        Node *currentNode = head;
        while (currentNode->next != nullptr) {
            currentNode = currentNode->next;
        }
        currentNode->next = newNode;
    }
}

int LinkedList::length() {
    int count = 0;
    Node* currentNode = head;
    while(currentNode != nullptr) {
        count ++;
        currentNode = currentNode->next;
    }
    return count;
}

void LinkedList::print() {
    Node* currentNode = head;
    while (currentNode != nullptr) {
        std::cout << currentNode->data << " ";
        currentNode = currentNode->next;
    }
    std::cout << "\n";
}
  • data를 포함한 head 노드 사용
  • friend 키워드를 통해 LinkedList 클래스에서 Node 클래스의 private 프로퍼티(data, next)에 접근 가능
  • 데이터를 처음 넣을 땐 head에 넣고, 그렇지 않은 경우 head부터 다음 노드가 nullptr일 때까지 이동한 후 새로운 노드를 next로 연결, 새로운 노드의 next는 nullptr

0개의 댓글