From 1e78677a776391777a30fd35a0941d98a0c0acf5 Mon Sep 17 00:00:00 2001 From: Ashwek Swamy <39827514+ashwek@users.noreply.github.com> Date: Wed, 9 Jan 2019 20:31:55 +0530 Subject: [PATCH] Update Linked List.cpp --- Datastructures/Linked List.cpp | 38 +++++++++++++++++++++++++--------- 1 file changed, 28 insertions(+), 10 deletions(-) diff --git a/Datastructures/Linked List.cpp b/Datastructures/Linked List.cpp index 9319249fd..02a2523ee 100644 --- a/Datastructures/Linked List.cpp +++ b/Datastructures/Linked List.cpp @@ -32,17 +32,33 @@ void insert(int x) } } -void remove(int x) -{ - node *t=start; - node *p; - while(t->val!=x) - { - p=t; - t=t->next; +void remove(int x){ + + if( start == NULL ){ + cout<<"\nLinked List is empty\n"; + return ; } - p->next=t->next; - delete t; + else if( start->val == x ){ + node *temp = start; + start = start->next; + delete temp; + return ; + } + + node *temp = start, *parent = start; + + while( temp != NULL && temp->val != x ){ + parent = temp; + temp = temp->next; + } + + if( temp == NULL ){ + cout <next = temp->next; + delete temp; } void search(int x) @@ -85,6 +101,7 @@ int main() cout<<"\n2. Delete"; cout<<"\n3. Search"; cout<<"\n4. Print"; + cout<<"\n5. Exit"; cout<<"\n\nEnter you choice : "; cin>>choice; switch (choice) @@ -99,6 +116,7 @@ int main() cin>>x; search(x); break; case 4 : show(); break; + case 5 : exit(0); } } while(choice!=0);