Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 2

#include <iostream>

using namespace std;

class Node{
public:
int data;
Node* next;
};

int push(Node** head_ref,int newdata){


Node* newnode=new Node();
newnode->data=newdata;
newnode->next=*head_ref;
*head_ref=newnode;
return 0;
}

int insertafter(Node** head_ref,int newdata,int b){


int count=0;
Node* newnode=new Node();
newnode->data=newdata;
Node* last=*head_ref;
while(last!=NULL){
count++;
last=last->next;
}
last=*head_ref;
if(b>0 && b<=count){
for(int i=1;i<b;i++){
last=last->next;
}
newnode->next=last->next;
last->next=newnode;
return 0;
}
else{
if(b==0){
cout<<"Node can be inserted after 1st node"<<endl;
return 0;
}
else{
cout<<"Node cannot be inserted after "<<b<<" as there are a total of
"<<count<<" nodes"<<endl;

return 0;
}
}
return 0;
}

int append(Node** head_ref,int newdata){


Node* newnode=new Node();
newnode->data=newdata;
newnode->next=NULL;
Node* last=*head_ref;
if(*head_ref==NULL){
*head_ref=newnode;
return 0;
}
while(last->next!=NULL){
last=last->next;
}
last->next=newnode;
return 0;
}

int delt(Node** head_ref,int a){


Node* last=*head_ref;
if(a==1){
*head_ref=last->next;
free(last);
return 0;
}
for(int i=2;i<a;i++){
last=last->next;
}
Node* temp=last->next;
last->next=last->next->next;
free(temp);
return 0;
}

int printList(Node* last){


while(last != NULL){
cout<<last->data<<" ";
last=last->next;
}
}

int main() {
Node* head=NULL;
append(&head,1);
append(&head,3);
push(&head,0);
insertafter(&head,2,2);
append(&head,5);
insertafter(&head,4,4);
delt(&head,6);
insertafter(&head,10,4);
delt(&head,6);
printList(head);
return 0;
}

You might also like