Hi, I am Aman Kumar pursuing BCA II. I have decided to write what i learn daily.
I request you to please go through this program and feel free to write me if you have any advice/suggestions for me at 2022amankumar@gmail.com
Implementing linked list:-
#include<iostream>
using namespace std;
struct Node //node
{
int data;
Node *next;
};
class linkedlist{ //linkedlist class
public:
Node* head;
linkedlist()
{
head=NULL;
}
void insert(int x) //inserting element in list when node is not specified
{
Node* tmp=new Node;
tmp->data=x;
tmp->next=head;
head=tmp;
}
void insert(int x,int n) //inserting element in list when node is specified
{
Node *temp=new Node;
temp->data=x;
temp->next=NULL;
if(n==1)
{
temp->next=head;
head=temp;
return;
}
Node *temp1=head;
for(int i=0;i<n-2;i++)
temp1=temp1->next;
temp->next=temp1->next;
temp1->next=temp;
}
void Delete(int n) //deleting node
{
Node *temp=head;
if(n==1)
{
head=temp->next;
delete temp;
return;
}
for(int i=0;i<n-2;i++)
temp=temp->next;
Node *temp1=temp->next;
temp->next=temp1->next;
delete temp1;
}
void Print() //printing elements
{
Node *tmp=head;
cout<<"The list is: ";
while(tmp!=NULL)
{
cout<<tmp->data<<" ";
tmp=tmp->next;
}
printf("\n");
}
void inverse() //inversing list using iteration
{
Node *current,*prev,*nextt;
current=head;
prev=NULL;
while(current!=NULL)
{
nextt=current->next;
current->next=prev;
prev=current;
current=nextt;
}
head=prev;
}
void Print(Node* p) //printing using recursion
{
if(p==NULL)
return;
cout<<p->data<<endl;
Print(p->next);
}
};
int main()
{
linkedlist tmp;
tmp.insert(23,1);
tmp.insert(23);
tmp.insert(45);
tmp.insert(50);
tmp.insert(37,3);
tmp.Print();
tmp.inverse();
tmp.Print();
tmp.Print(+)
}
Comments
Post a Comment