From a27fdb30ddd316a3a1f33f07d618e5bf59a378f7 Mon Sep 17 00:00:00 2001 From: Visrut Date: Sat, 30 Jan 2021 17:57:49 +0530 Subject: [PATCH] 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 --- .gitignore | 8 ++- linked-lists/README.md | 5 ++ linked-lists/c-or-cpp/SinglyLinkedList.cpp | 79 ++++++++++++++++++++++ 3 files changed, 90 insertions(+), 2 deletions(-) create mode 100644 linked-lists/README.md create mode 100644 linked-lists/c-or-cpp/SinglyLinkedList.cpp 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; +}