From 861b2914444e783bdafee997999b552cf5e85abf Mon Sep 17 00:00:00 2001 From: anushaka1272 <53932394+anushaka1272@users.noreply.github.com> Date: Tue, 6 Oct 2020 13:54:14 +0530 Subject: [PATCH] Update linked_list.cpp Add Insert after N pos function --- linked_list.cpp | 59 ++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 58 insertions(+), 1 deletion(-) diff --git a/linked_list.cpp b/linked_list.cpp index 425405f..5573fef 100644 --- a/linked_list.cpp +++ b/linked_list.cpp @@ -125,6 +125,54 @@ class linkedlist } } } + + void insert_after_pos(T n, int pos) + { + Node* temp = head; + Node* N = new Node(element); + + int index = 0; + + if(head==NULL) + { + cout<<"\nInvalid Position"; + } + + else if(head==tail) + { + tail->next=N; + tail=N; + } + else + { + while(1) + { + index++; + if(index==pos) + break; + temp=temp->next; + + if(temp->next==NULL) + { + cout<<"\nOUT"; + break; + } + + } + + if(temp->next==NULL) + { + tail->next=N; + tail=N; + } + else + { + N->next=temp->next; + temp->next=N; + } + } + + } void search(T n) { int k=0; @@ -161,7 +209,7 @@ class linkedlist }; int main() { - int n,q; + int n,q,pos; char e; char a='y'; linkedlist list; @@ -175,6 +223,7 @@ int main() <<"4. Delete the element from the tail\n" <<"5. Search the element in the linked list\n" <<"6. Traverse the linked list\n"; + <<"7. Insert element after N pos\n"; cout<<"\n\nEnter your choice: "; cin>>q; switch (q) @@ -213,6 +262,14 @@ int main() case 6: list.traverse(); break; + + case 7: + cout<<"Enter Element: "; + cin>>n; + cout<<"\nEnter Position: "; + cin>>pos; + insert_after_pos(n,pos); + break; } cout<<"\n\nDo you want to continue if yes press 'y' ,if no press 'n': "; cin>>a;