Add method to single linkedlist (#75)
* Update singly.cpp Add the `insertAtEnd()` method to single linkedlist. * Update singly.cpppull/78/head
parent
b48084de34
commit
5938a1def4
|
@ -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>
|
||||||
|
@ -34,6 +35,27 @@ class SinglyLinkedList {
|
||||||
// change head point to new node
|
// change head point to new node
|
||||||
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
|
||||||
|
@ -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;
|
||||||
|
|
Loading…
Reference in New Issue