diff --git a/.gitignore b/.gitignore index 863ca25e..a1c09e19 100644 --- a/.gitignore +++ b/.gitignore @@ -1,8 +1,12 @@ -# OS generated files +# OS generated files .DS_Store .DS_Store? ._* .Spotlight-V100 .Trashes ehthumbs.db -Thumbs.db \ No newline at end of file +Thumbs.db + +# binary files +*.out +*.class diff --git a/linked-lists/README.md b/linked-lists/README.md new file mode 100644 index 00000000..f8185d42 --- /dev/null +++ b/linked-lists/README.md @@ -0,0 +1,5 @@ +# Linked Lists + +### c or c++ + +1. [Singly Linked List](c-or-cpp/SinglyLinkedList.cpp) diff --git a/linked-lists/c-or-cpp/SinglyLinkedList.cpp b/linked-lists/c-or-cpp/SinglyLinkedList.cpp new file mode 100644 index 00000000..019e8174 --- /dev/null +++ b/linked-lists/c-or-cpp/SinglyLinkedList.cpp @@ -0,0 +1,79 @@ +#include + +template +class Node { + public: + T data; + Node *next; + + Node(T data) + : data(data) , next(nullptr) {}; +}; + +template +class SinglyLinkedList { + private: + Node* head; + + public: + SinglyLinkedList() + : head(nullptr){} + + void insertAtHead(T data) { + Node *temp = new Node(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"<head->data; + // save temp pointer to free the memory + Node* 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"< *itr = this->head; + // iterate through list until itr reach to nullptr and print data + while(itr != nullptr) { + std::cout<data<<" "; + itr = itr->next; + } + std::cout< l; + l.insertAtHead(1); + l.insertAtHead(2); + l.insertAtHead(3); + l.removeAtHead(); + l.printList(); + return 0; +}