
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";
}