enh(CPlusPlus): insertion at end (#433)

pull/438/head
shinchancode 2021-08-30 00:51:24 +05:30 committed by GitHub
parent 1eea787f5e
commit d161d858e8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 7 additions and 9 deletions

View File

@ -15,10 +15,11 @@ template <typename T>
class SinglyLinkedList { class SinglyLinkedList {
private: private:
Node<T>* head; Node<T>* head;
Node<T>* tail;
public: public:
SinglyLinkedList() SinglyLinkedList()
: head(nullptr){} : head(nullptr),tail(nullptr){}
void insertAtHead(T data) { void insertAtHead(T data) {
Node<T> *temp = new Node<T>(data); Node<T> *temp = new Node<T>(data);
@ -43,18 +44,15 @@ class SinglyLinkedList {
// if head is not pointing to anything then simply point to new node // if head is not pointing to anything then simply point to new node
if(this->head == nullptr) { if(this->head == nullptr) {
this->head = newNode; this->head = newNode;
this->tail = newNode;
return; return;
} }
// if list is not empty, then traverse to the last node using `temp`, then put the address of the new node in the temp->next // if list is not empty, then put the address of the new node in the tail->next
// and finally, make the next of newNode = NULL // and finally, make the next of newNode = NULL and tail will be pointing the the newNode as now it is in the last position.
Node<T> *temp = new Node<T>(); tail->next = newNode;
temp = head;
while(temp->next != NULL){
temp = temp->next;
}
temp->next = newNode;
newNode->next= NULL; newNode->next= NULL;
tail=newNode;
} }
T removeAtHead() { T removeAtHead() {