I saw the code in the C++ book and followed it. But I want to add and remove objects in this code. What should I do? I'm really a beginner.ㅠ<
#include<cstdlib>
#include<iostream>
using namespace std;
class StringNode {
private:
string elem;
StringNode* next;
friend class StringLinkedList;
};
class StringLinkedList {
public:
StringLinkedList();
~StringLinkedList();
bool empty() const;
const string& front() const;
void addFront(const string& e);
void removeFront();
private:
StringNode* head;
};
StringLinkedList::StringLinkedList()
: : head(NULL) { }
StringLinkedList::~StringLinkedList()
{
while (!empty()) removeFront();
}
bool StringLinkedList::empty() const
{
return head == NULL;
}
const string& StringLinkedList::front() const
{
return head->elem;
}
void StringLinkedList::addFront(const string& e) {
StringNode* v = new StringNode;
v->elem = e;
v->next = head;
head = v;
}
void StringLinkedList::removeFront() {
StringNode* old = head;
head = old->next;
delete old;
}
int main() {
StringNode A();
StringLinkedList B();
}
Please refer to the code below.
#include<cstdlib>
#include<iostream>
using namespace std;
class StringNode {
private:
string elem;
StringNode* next;
friend class StringLinkedList;
};
class StringLinkedList {
public:
StringLinkedList();
~StringLinkedList();
bool empty() const;
const string& front() const;
void addFront(const string& e);
void removeFront();
private:
StringNode* head;
};
StringLinkedList::StringLinkedList()
: : head(NULL) { }
StringLinkedList::~StringLinkedList()
{
while (!empty()) removeFront();
}
bool StringLinkedList::empty() const
{
return head == NULL;
}
const string& StringLinkedList::front() const
{
return head->elem;
}
void StringLinkedList::addFront(const string& e) {
StringNode* v = new StringNode;
v->elem = e;
v->next = head;
head = v;
}
void StringLinkedList::removeFront() {
StringNode* old = head;
head = old->next;
delete old;
}
int main() {
StringLinkedList list;
list.addFront("hello");
list.addFront("hi");
list.addFront ("Hello");
list.addFront ("Let's go");
list.addFront("123");
while (!list.empty())
{
cout << list.front() << '\n';
list.removeFront();
}
return 0;
}
© 2024 OneMinuteCode. All rights reserved.