LinkList with double Pointers



Here is a implementation of insertion (before/after node) and deletion of nodes with double pointers. I have also written a function to reverse the linklist.
#include
using namespace std;
struct box{
int data;
box *next;
};
box *head = NULL;
box* getNode(int val){
box *temp = new box;
temp->data=val;
temp->next=NULL;
return temp;
}
void insert_after_ll(box **pp, int val){
box *node = getNode(val);
while(*pp){
pp = &(*pp)->next;
}
*pp = node;
}
void insert_before_ll(box **pp, int val){
box *node = getNode(val);
node->next = *pp;
*pp = node;
}
void delete_ll(box **pp, int val){
box *trav = head;
while(trav){
if(trav->data == val)
*pp = trav->next;
pp = &(trav)->next;
trav = trav->next;
}
}
void reverse_ll(){
box *p=NULL,*c=head,*n=NULL;
while(c!=NULL){
n=c->next;
c->next = p;
p=c;
c=n;
}
head=p;
}
void print_ll(box *refr){
while(refr){
cout << refr->data << " ";
refr = refr->next;
}
cout << endl;
}
int main(){
for(int i=0;i<5;i++)
insert_before_ll(&head,i);
for(int i=5;i<10;i++)
insert_after_ll(&head,i);
print_ll(head);
reverse_ll();
delete_ll(&head,9);
print_ll(head);
return 0;
}

OUTPUT

4 3 2 1 0 5 6 7 8 9
8 7 6 5 0 1 2 3 4

Suhaib Bin Younis | @suhaibbinyounis

Post a Comment

Post a Comment (0)

Previous Post Next Post