Data Structures (#44)

* added singly linked list in c++

* changed .gitignore to ignore binary files for c++ and java

* changed .gitignore to ignore binary files for c++ and java

* i changed as per review , method names in SinglyLinkedList and folder name

* i changed directory name as per convention
pull/52/head
Visrut 2021-01-30 17:57:49 +05:30 committed by GitHub
parent bbec0ebacf
commit a27fdb30dd
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 90 additions and 2 deletions

8
.gitignore vendored
View File

@ -1,8 +1,12 @@
# OS generated files # OS generated files
.DS_Store .DS_Store
.DS_Store? .DS_Store?
._* ._*
.Spotlight-V100 .Spotlight-V100
.Trashes .Trashes
ehthumbs.db ehthumbs.db
Thumbs.db Thumbs.db
# binary files
*.out
*.class

View File

@ -0,0 +1,5 @@
# Linked Lists
### c or c++
1. [Singly Linked List](c-or-cpp/SinglyLinkedList.cpp)

View File

@ -0,0 +1,79 @@
#include <iostream>
template <typename T>
class Node {
public:
T data;
Node *next;
Node(T data)
: data(data) , next(nullptr) {};
};
template <typename T>
class SinglyLinkedList {
private:
Node<T>* head;
public:
SinglyLinkedList()
: head(nullptr){}
void insertAtHead(T data) {
Node<T> *temp = new Node<T>(data);
// if head is not pointing to anything then simply point to new node
if(this->head == nullptr) {
this->head = temp;
return;
}
// if head is already point at some node
// first make new node points to head address
temp->next = this->head;
// change head point to new node
this->head = temp;
}
T removeAtHead() {
// if list is empty we can't remove node
if(this->head == nullptr) {
std::cout<<"List is Empty"<<std::endl;
exit(1);
}
// save data of node where head is pointed
T data = this->head->data;
// save temp pointer to free the memory
Node<T>* temp_ptr = this->head;
this->head = this->head->next;
// free memory
delete temp_ptr;
return data;
}
void printList() const {
if(this->head == nullptr) {
std::cout<<"List is Empty"<<std::endl;
} else {
Node<T> *itr = this->head;
// iterate through list until itr reach to nullptr and print data
while(itr != nullptr) {
std::cout<<itr->data<<" ";
itr = itr->next;
}
std::cout<<std::endl;
}
}
};
int main() {
SinglyLinkedList<int> l;
l.insertAtHead(1);
l.insertAtHead(2);
l.insertAtHead(3);
l.removeAtHead();
l.printList();
return 0;
}