From 268567d2e1dea0ade7aa771fe51a19ddf4907809 Mon Sep 17 00:00:00 2001 From: Shinh18 Date: Mon, 26 Oct 2020 18:44:27 -0400 Subject: [PATCH] Add Sentinel linked list implementation --- LINKED_LIST/SentinelLinkedList.cpp | 87 ++++++++++++++++++++++++++++++ 1 file changed, 87 insertions(+) create mode 100644 LINKED_LIST/SentinelLinkedList.cpp diff --git a/LINKED_LIST/SentinelLinkedList.cpp b/LINKED_LIST/SentinelLinkedList.cpp new file mode 100644 index 0000000..31d668d --- /dev/null +++ b/LINKED_LIST/SentinelLinkedList.cpp @@ -0,0 +1,87 @@ +#include + +template +class Sentinel { + struct Node { + T data_; + Node* next_; + Node* prev_; + Node(const T& data=T{}, Node* next = nullptr, Node* prev = nullptr) { + data_ = data; + next_ = next; + prev_ = prev; + } + }; + Node* front_; + Node* back_; +public: + Sentinel() { + front_ = new Node(); + back_ = new Node(); + front_->next_ = back_; + back_->prev_ = front_; + } + void insert_front(const T& data); + void insert_back(const T& data); + void delete_front(); + void delete_back(); + void print() const; + ~Sentinel(); +}; + +template +void Sentinel::insert_front(const T& data) { + Node* newNode = new Node(data, front_->next_, front_); + front_->next_->prev_ = newNode; + front_->next_ = newNode; +} + +template +void Sentinel::insert_back(const T& data) { + Node* newNode = new Node(data, back_, back_->prev_); + back_->prev_->next_ = newNode; + back_->prev_ = newNode; +} + +template +void Sentinel::delete_front() { + if(front_->next != back_) { + Node* rm = front_->next_; + front_->next_ = rm->next_; + rm->next_->prev_ = front_; + delete rm; + } +} + +template +void Sentinel::delete_back() { + if(front_->next_ != back_) { + Node* rm = back_->prev_; + back_->prev_ = rm->prev_; + back_->prev_->next_ = back_; + delete rm; + } +} + +template +void Sentinel::print() const { + Node* curr = front_->next_; + while(curr != back_) { + std::cout << curr->data_ << " "; + curr = curr->next_; + } + if(front_->next_ == back_) { + std::cout << "empty list"; + } + std::cout << std::endl; +} + +template +Sentinel::~Sentinel() { + Node* curr = front_->next_; + while(curr != back_) { + Node* rm = curr; + curr = curr->next_; + delete rm; + } +} \ No newline at end of file