Skip to content
This repository has been archived by the owner on Jul 9, 2021. It is now read-only.

Commit

Permalink
Add Sentinel linked list implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
mshinh committed Oct 26, 2020
1 parent cd37802 commit 268567d
Showing 1 changed file with 87 additions and 0 deletions.
87 changes: 87 additions & 0 deletions LINKED_LIST/SentinelLinkedList.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
#include <iostream>

template <typename T>
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 <typename T>
void Sentinel<T>::insert_front(const T& data) {
Node* newNode = new Node(data, front_->next_, front_);
front_->next_->prev_ = newNode;
front_->next_ = newNode;
}

template <typename T>
void Sentinel<T>::insert_back(const T& data) {
Node* newNode = new Node(data, back_, back_->prev_);
back_->prev_->next_ = newNode;
back_->prev_ = newNode;
}

template <typename T>
void Sentinel<T>::delete_front() {
if(front_->next != back_) {
Node* rm = front_->next_;
front_->next_ = rm->next_;
rm->next_->prev_ = front_;
delete rm;
}
}

template <typename T>
void Sentinel<T>::delete_back() {
if(front_->next_ != back_) {
Node* rm = back_->prev_;
back_->prev_ = rm->prev_;
back_->prev_->next_ = back_;
delete rm;
}
}

template <typename T>
void Sentinel<T>::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 <typename T>
Sentinel<T>::~Sentinel() {
Node* curr = front_->next_;
while(curr != back_) {
Node* rm = curr;
curr = curr->next_;
delete rm;
}
}

0 comments on commit 268567d

Please sign in to comment.