diff --git a/algorithms/CPlusPlus/Linked-Lists/remove-specific-elements.cpp b/algorithms/CPlusPlus/Linked-Lists/remove-specific-elements.cpp new file mode 100644 index 00000000..d6e73016 --- /dev/null +++ b/algorithms/CPlusPlus/Linked-Lists/remove-specific-elements.cpp @@ -0,0 +1,118 @@ +#include + +using namespace std; + +//node class to store nodes +class Node{ + + public: + + int data; + Node* next; +}; + + +//creating linked list from given vector +void Create(vectorv,Node*& head){ + Node* prev; + for(int i=0;inext=nullptr; + temp->data=v[i]; + + if(i==0){ + head=temp; + + }else{ + prev->next=temp; + } + prev=temp; + } + + +} + +//display linked list +void Display(Node*& head){ + + if(head==nullptr) cout<<"\nEmpty"; + Node* temp=head; + + while(temp){ + cout<data; + temp=temp->next; + } + cout<<"\n"; + +} + +//delete Node of specific values +void RemNode(Node*& head,int val){ + + Node* temp=head; + + while(head && head->data==val){ + //while head is equal to value move pointer + head=head->next; + + } + + while(temp){ + + if(temp->next&&temp->next->data==val){ //same for rest of the nodes if val of next is equal to val then move ahead + + temp->next=temp->next->next; + + + + }else{ + temp=temp->next; //else just iterate + } + } + + + +} + +int main(){ + + Node* head=NULL; + int n,val; + cout<<"\nEnter no. of elements in linked list "; //Input vector size and elements + cin>>n; + vectorv(n); + cout<<"\nEnter elements of linked list "; + for(int i=0;i>v[i]; + + } + cout<<"\nLinked list is:- "; + Create(v,head); + Display(head); + cout<<"\nElement to remove "; + cin>>val; + + RemNode(head,val); + cout<<"\nLinked list after removing:- "; + Display(head); + return 0; +} + +/* + +Time Complexity-O(n) + +Enter no. of elements in linked list 6 + +Enter elements of linked list 3 2 4 3 6 3 + +Linked list is:- 324363 + +Element to delete 3 + +Linked list after deletion:- 246 + + +*/ \ No newline at end of file diff --git a/algorithms/CPlusPlus/README.md b/algorithms/CPlusPlus/README.md index 224c8fcf..1caab779 100644 --- a/algorithms/CPlusPlus/README.md +++ b/algorithms/CPlusPlus/README.md @@ -34,9 +34,10 @@ 2. [Singly linked lists](Linked-Lists/singly.cpp) 3. [doubley linked lists](Linked-Lists/doubly.cpp) 4. [Circular linked lists](Linked-Lists/circular.cpp) -5. [Reversing a linked lists](Linked-Lists/reverse.cpp) -6. [Merging two sorted linked lists](Linked-Lists/merge.cpp) -6. [Reorder List](Linked-Lists/Reorder-List.cpp) +5. [Removing Elements of given value](Linked-Lists/remove-specific-elements.cpp) +6. [Reversing a linked lists](Linked-Lists/reverse.cpp) +7. [Merging two sorted linked lists](Linked-Lists/merge.cpp) +8. [Reorder List](Linked-Lists/Reorder-List.cpp) ## Searching