Refactor code structure for improved readability and maintainability
This commit is contained in:
80
demos/lists/cpp/main.cpp
Normal file
80
demos/lists/cpp/main.cpp
Normal file
@@ -0,0 +1,80 @@
|
||||
#include <iostream>
|
||||
#include <optional>
|
||||
|
||||
// A single node containing data and a raw pointer to the next node
|
||||
template <typename T>
|
||||
struct Node {
|
||||
T data;
|
||||
Node<T>* next;
|
||||
};
|
||||
|
||||
// The main wrapper for the linked list tracking the head node
|
||||
template <typename T>
|
||||
class LinkedList {
|
||||
public:
|
||||
LinkedList() : head_(nullptr) {}
|
||||
|
||||
~LinkedList() {
|
||||
Node<T>* current = head_;
|
||||
while (current) {
|
||||
Node<T>* next = current->next;
|
||||
delete current;
|
||||
current = next;
|
||||
}
|
||||
}
|
||||
|
||||
// Raw-pointer ownership can't be safely duplicated by a shallow copy
|
||||
LinkedList(const LinkedList&) = delete;
|
||||
LinkedList& operator=(const LinkedList&) = delete;
|
||||
|
||||
// Add a new element to the front of the list
|
||||
void push_front(T data) {
|
||||
head_ = new Node<T>{std::move(data), head_};
|
||||
}
|
||||
|
||||
// Remove and return the front element of the list
|
||||
std::optional<T> pop_front() {
|
||||
if (!head_) {
|
||||
return std::nullopt;
|
||||
}
|
||||
Node<T>* old_head = head_;
|
||||
T data = std::move(old_head->data);
|
||||
head_ = old_head->next;
|
||||
delete old_head;
|
||||
return data;
|
||||
}
|
||||
|
||||
// Read the front element without removing it
|
||||
const T* peek_front() const {
|
||||
return head_ ? &head_->data : nullptr;
|
||||
}
|
||||
|
||||
private:
|
||||
Node<T>* head_;
|
||||
};
|
||||
|
||||
int main() {
|
||||
LinkedList<int> list;
|
||||
int count=0;
|
||||
char * message1 = "hello world";
|
||||
// Demonstrate pushing items
|
||||
list.push_front(10);
|
||||
count++;
|
||||
list.push_front(20);
|
||||
count++;
|
||||
list.push_front(30);
|
||||
count++;
|
||||
|
||||
// Demonstrate peeking at the top item
|
||||
if (const int* top = list.peek_front()) {
|
||||
std::cout << "Top element: " << *top << "\n"<<"count: "<<count<<"\n"; // Output: 30
|
||||
}
|
||||
std::cout<<message1<<"\n";
|
||||
|
||||
// Demonstrate popping items
|
||||
while (auto value = list.pop_front()) {
|
||||
std::cout << "Popped: " << *value << "\n";
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
Reference in New Issue
Block a user