#include <iostream>
#include "class.h"
using namespace std;
void List::addToBeginning(ListElement* element)
{
element->next = this->firstElement;
this->firstElement = element;
size++;
}
void List::addToBeginning(int key)
{
ListElement* el = new ListElement(key);
this->addToBeginning(el);
}
void List::addToEnd(ListElement* element) {
if (!this->firstElement)
this->firstElement = element;
else {
ListElement* tmp = this->firstElement;
while (tmp->next)
tmp = tmp->next;
tmp->next = element;
}
size++;
}
void List::addToEnd(int key) {
ListElement* el = new ListElement(key);
this->addToEnd(el);
}
ListElement* List::getElement(int key) {
ListElement* el = this->firstElement;
while (el) {
if (el->getKey() == key) break;
el = el->next;
}
return el;
}
int ListElement::getKey() {
return this->key;
}
bool List::contains(int key) {
if (getElement(key)) return true;
else return false;
}
void List::removeKey(int key){
if (this->contains(key)) {
if (size == 1) {
this->firstElement = NULL;
size--;
}
else {
ListElement* el = getElement(key);
if (!el->next) el = NULL;
else {
*el = *el->next;
size--;
}
}
}
}
void List::clearAll() {
ListElement* tmp = this->firstElement;
while (this->firstElement) {
this->firstElement = this->firstElement->next;
delete tmp;
tmp = this->firstElement;
}
cout << "Dane z listy usuniete\n";
}
void List::PrintList() {
ListElement* tmp = this->firstElement;
while (this->firstElement) {
this->firstElement = this->firstElement->next;
cout << " data = " << tmp->key << endl;
tmp = this->firstElement;
}
}
ListElement::ListElement(int key) {
this->key = key;
}
#include <iostream>
using namespace std;
class ListElement;
class List {
ListElement* firstElement = nullptr;
int size = 0;
public:
void addToBeginning(int key);
void addToBeginning(ListElement* element);
void addToEnd(int key);
void addToEnd(ListElement* element);
ListElement* getElement(int key);
bool contains(int key);
void removeKey(int key);
void clearAll();
void PrintList();
};
class ListElement {
int key;
ListElement* next;
public:
int getKey();
ListElement(int key);
friend class List;
};
#include <iostream>
#include "class.h"
using namespace std;
int main()
{
List* lista = new List();
lista->addToBeginning(3);
lista->addToEnd(2);
lista->PrintList();
lista->removeKey(2);
lista->addToBeginning(3);
lista->PrintList();
}
Witam chciałem napisać obiektowo listę jednokierunkową. Obecnie nie działają mi poprawnie funkcje contains, oraz removekey i szczerze nie mam już na nie pomysłu. Każda pomoc będzie dobra.