LL Class 4: Insert Operation
// Online C++ compiler to run C++ program online
#include <iostream>
using namespace std;
struct node{
public:
int data;
node* next;
node(int data){
this->data=data;
next=NULL;
}
};
void display(node* head){
node* temp=head;
while(temp!=NULL){
cout<<temp->data<<" ";
temp=temp->next;
}
}
node* input_optimal(){
int data;
cin>>data;
node* head=NULL;
node*tail=NULL;
while(data!=-1){
node*n=new node(data);
if (head==NULL){
head=n;
tail=n;
}
else{
tail->next=n;
//tail=tail->next;
//OR
tail=n;
}
cin>>data;
}
return head;
}
int length(node *head)
{
//Write your code here
int count=0;
node* temp=head;
while(temp!=NULL){
count++;
temp=temp->next;
}
return count;
}
node* insertnode(node* head, int i, int data){
node* n=new node(data);
int count=0;
node* temp=head;
if(i==0){
n->next=head;
head=n;
return head;
}
while(temp!=NULL && count<i-1){
temp=temp->next;
count++;
}
if (temp!=NULL){
n->next=temp->next;
temp->next=n;
}
return head;
}
int main() {
node*head=input_optimal();
display(head);
cout<<endl;
head=insertnode(head,0,100);
display(head);
return 0;
}
Comments
Post a Comment