Linked list C++



#include "LinkedList.h"
#include "strlib.h"



LinkedList::LinkedList() {
    m_front = NULL;
    m_size = 0;
}

LinkedList::~LinkedList() {
    if(!m_front == NULL){
        while(!current->next == NULL){
            trash = current->next;
            delete trash;
        }

    }
    m_front = NULL;
    m_size = 0;
   
}

void LinkedList::add(int value) {
    if (m_front == NULL) {
        // empty list: add this node as the new front
        m_front = new ListNode(value, NULL);
    } else {
        // non-empty list: move to end, attach new node
        ListNode* current = m_front;
        while (current->next != NULL) {
            current = current->next;
        }
        current->next = new ListNode(value, NULL);
    }
    m_size++;
}

void LinkedList::clear() {
    while(current->next != NULL){
        delete current;
    }
   
}

int LinkedList::get(int index) const {
    ListNode* current = m_front;
    for (int i = 0; i < index; i++)
    {
       current = current->next;
    }
    return current->data;
}

void LinkedList::insert(int index, int value) {
    if (index == 0){
        m_front = new ListNode(value, m_front);
    } else {
        ListNode* current = m_front;
        for (int i = 0; i < index; i++)
        {
           current = current->next;
        }
        current->next = new ListNode(value, current->next);
    }
   
}



bool LinkedList::isEmpty() const {
    return m_size == 0;
}

void LinkedList::remove(int index) {
    if (index == 0) {
        // removing the front node
        m_front = m_front->next;
    } else {
        // removing a node further along in the list
        ListNode* curr = m_front;
        for (int i = 0; i < index-1; i++) {
            curr = curr->next;
        }
        curr->next = curr->next->next;
    }
    m_size--;
}

void LinkedList::set(int index, int value) {
    if (index == 0){
        m_front = new ListNode(value, m_front);
    } else {
        ListNode* current = m_front;
        for (int i = 0; i < index; i++)
        {
           current = current->next;
        }
        current->data = value;
    }
   
   
}

void LinkedList::addSorted(int value){
    if(m_front == NULL || value < m_front->data){
        m_front = new ListNode(value, m_front);
    } else {
        ListNode* current = m_front;
        while(current->next != NULL && current->next->data < value){
            current = current->next;
        }
    }
}

int LinkedList::size() const {
    return m_size;
}

string LinkedList::toString() const {
    string result = "[";
    if (!isEmpty()) {
        result += integerToString(m_front->data);
        ListNode* curr = m_front->next;
        while (curr != NULL) {
            result += ", " + integerToString(curr->data);
            curr = curr->next;
        }
    }
    return result + "]";
}

Comments

Popular posts from this blog

Внизу Сванетия

До свидания