diff --git a/Data-Structures/LinkedList.cpp b/Data-Structures/LinkedList.cpp new file mode 100644 index 0000000..b54a3f1 --- /dev/null +++ b/Data-Structures/LinkedList.cpp @@ -0,0 +1,95 @@ +/* Linked List +This is basic data structure which helps you to understand +the way of writing data structures. It may be basic but presents +many concepts of dynamic structures + +Insert: O(n) +Find: O(n) +Delete: O(n) +Change Element: O(n) +Print: O(n) +*/ + +#include + +using namespace std; + +struct LinkedList +{ + int value; + LinkedList *next; + LinkedList(int val) + { + this->value=val; + this->next=NULL; + } +}; + +void Insert(LinkedList *&root, int value) +{ + if(root==NULL) + { + root=new LinkedList(value); + } + else + { + LinkedList *tmp = root; + while(tmp->next!=NULL) + { + tmp = tmp->next; + } + tmp->next=new LinkedList(value); + } +} +LinkedList* Find(LinkedList *root, int value) +{ + while(root!=NULL && root->value!=value) + { + root=root->next; + } + return root; +} +void Delete(LinkedList *&root, int value) +{ + if(root==NULL)return; + if(root->value==value) + { + LinkedList *tmp = root; + root=root->next; + delete tmp; + } + LinkedList *tmp = root; + while(tmp!=NULL && tmp->next!=NULL && tmp->next->value!=value) + { + tmp=tmp->next; + } + if(tmp!=NULL) + { + LinkedList *tmp2 = tmp->next; + tmp->next = tmp->next->next; + delete tmp2; + } +} +void Print(LinkedList *root) +{ + while(root!=NULL) + { + cout<value<<" "; + root=root->next; + } + cout< + +using namespace std; + +struct Trie +{ + int childrenC; + Trie* children[30]; + bool endOfWord; + Trie() + { + this->childrenC=0; + this->endOfWord=false; + for(int i=0;i<30;i++) + { + this->children[i]=NULL; + } + } +}; +void Insert(Trie *&root, string word) +{ + Trie* tmp = root; + for(int i=0;ichildren[word[i]-'a']==NULL) + { + tmp->childrenC++; + tmp->children[word[i]-'a']=new Trie(); + } + tmp=tmp->children[word[i]-'a']; + if(i==word.size()-1) + { + tmp->endOfWord=true; + } + } +} +bool Check(Trie *root, string word) +{ + bool result=true; + for(int i=0;ichildren[word[i]-'a']==NULL) + { + result=false; + break; + } + root = root->children[word[i]-'a']; + if(i==word.size()-1) + { + result = root->endOfWord; + } + } + return result; +} +bool RemoveAPI(Trie* &cur,string word,int idx) +{ + if(cur==NULL)return false; + if(idx==word.size()) + { + cur->endOfWord=false; + } + else + { + bool result = RemoveAPI(cur->children[word[idx]-'a'],word,idx+1); + if(result) + { + cur->childrenC--; + delete cur->children[word[idx]-'a']; + } + } + return cur->childrenC==0; +} +void Remove(Trie* &root,string word) +{ + RemoveAPI(root,word,0); +} +int main() +{ + //Driver code. + Trie* root = new Trie(); + Insert(root,"test"); + Insert(root,"testa"); + cout<