enh(CPlusPlus): Add remove all elements of specific value in linked-list (#392)

Co-authored-by: Ujjwal <75884061+UG-SEP@users.noreply.github.com>
pull/394/head
Ellika Mishra 2021-07-23 18:00:26 +05:30 committed by GitHub
parent 460843a61a
commit 969bfa9387
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 122 additions and 3 deletions

View File

@ -0,0 +1,118 @@
#include<bits/stdc++.h>
using namespace std;
//node class to store nodes
class Node{
public:
int data;
Node* next;
};
//creating linked list from given vector
void Create(vector<int>v,Node*& head){
Node* prev;
for(int i=0;i<v.size();i++){
Node* temp=new Node();
temp->next=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<<temp->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;
vector<int>v(n);
cout<<"\nEnter elements of linked list ";
for(int i=0;i<n;i++){
cin>>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
*/

View File

@ -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