Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

random-insert-into-ll.cpp #197

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 70 additions & 0 deletions C++/RandomInsertIntoLL.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
#include<iostream>
using namespace std;
class node
{
public:
int val;
node* link;
}*head,*last;
void insert(int n,int pos)
{
node* temp=new node();
temp->val=n;
temp->link=NULL;
if(head==NULL)
head=temp;
else if(pos==1)
{
temp->link=head;
head=temp;
}
else{
node* tempr=head;
node* templ=NULL;
int c=0;
while(c<pos)
{
templ=tempr;
tempr=tempr->link;
c++;
}
if(tempr->link==NULL)
{
templ->link=temp;
temp->link=NULL;
}
else{
templ->link=temp;
temp->link=tempr;
}
}
}
void display()
{
node* temp=head;
while(temp)
{
cout<<temp->val<<" -> ";
temp=temp->link;
}
}
int main()
{
head=NULL;
last=NULL;
int n_ele=0;
while(true)
{
int x,pos;
cin>>pos>>x;
pos--;
if(pos<0 || pos>n_ele+1)
break;
display();
insert(x,pos);
display();
n_ele++;
}
cout<<"Invalid position"<<endl;
return 0;
}