Add method to single linkedlist (#75)

* Update singly.cpp

Add the `insertAtEnd()` method to single linkedlist.

* Update singly.cpp
pull/78/head
Tawfik Yasser 2021-02-17 02:53:04 +02:00 committed by GitHub
parent b48084de34
commit 5938a1def4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 23 additions and 0 deletions

View File

@ -8,6 +8,7 @@ class Node {
Node(T data) Node(T data)
: data(data) , next(nullptr) {}; : data(data) , next(nullptr) {};
Node(){}
}; };
template <typename T> template <typename T>
@ -35,6 +36,27 @@ class SinglyLinkedList {
this->head = temp; this->head = temp;
} }
void insertAtEnd(T data){
Node<T> *newNode = new Node<T>(data);
// if head is not pointing to anything then simply point to new node
if(this->head == nullptr) {
this->head = newNode;
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
// and finally, make the next of newNode = NULL
Node<T> *temp = new Node<T>();
temp = head;
while(temp->next != NULL){
temp = temp->next;
}
temp->next = newNode;
newNode->next= NULL;
}
T removeAtHead() { T removeAtHead() {
// if list is empty we can't remove node // if list is empty we can't remove node
if(this->head == nullptr) { if(this->head == nullptr) {
@ -73,6 +95,7 @@ int main() {
l.insertAtHead(1); l.insertAtHead(1);
l.insertAtHead(2); l.insertAtHead(2);
l.insertAtHead(3); l.insertAtHead(3);
l.insertAtEnd(5);
l.removeAtHead(); l.removeAtHead();
l.printList(); l.printList();
return 0; return 0;