enh(CPlusPlus): insertion at end (#433)
parent
1eea787f5e
commit
d161d858e8
|
@ -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() {
|
||||||
|
|
Loading…
Reference in New Issue