Insertion Revision
// 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;
}
cout<<"NULL"<<endl;
}
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;
}
node* insert_node(node*head,int i, int data){
node*temp=head;
node*n=new node(data);
int count=0;
if (i==0){
n->next=head;
head=n;
return head;
}
else{
while(count<i-1 && temp!=NULL){
temp=temp->next;
count++;
}
if (temp!=NULL){
n->next=temp->next;
temp->next=n;
}
}
return head;
}
int main() {
node*head=input_optimal();
display(head);
head=insert_node(head,6,99);
display(head);
return 0;
}
Comments
Post a Comment