Singly Linked List in (C++)
#include<iostream>
using namespace std;
struct Node
{
int data;
Node *next;
Node *prev;
};
Node *Head=NULL;
Node *Tail=NULL;
Node *createNewNode(int value)
{
Node *newNode=new Node;
newNode->data=value;
newNode->next=NULL;
newNode->prev=NULL;
return newNode;
}
int getValue()
{
int x;
cout<<"Enter Input:";
cin>>x;
return x;
}
void createList(int total)
{
Node *currNode=Head=Tail=createNewNode(getValue());
for(int i=1;i<total;i++)
{
Node *newNode=createNewNode(getValue());
currNode->next = newNode;
newNode->prev = currNode;
Tail = newNode;
currNode=currNode->next;
}
}
void show()
{
Node *currNode=Head;
while(currNode!=NULL)
{
cout<<currNode->data<< " ";
currNode=currNode->next;
}
}
void reverse_show()
{
Node *currNode=Tail;
while(currNode!=NULL)
{
cout<<currNode->data<< " ";
currNode=currNode->prev;
}
}
void insertfirst(int v)
{
Node *currNode=createNewNode(v);
currNode->next=Head;
Head=currNode;
}
void insertLast(int v)
{
Node *currNode=Head;
while(currNode->next!=NULL)
{
currNode=currNode->next;
}
Node *newNode=createNewNode(v);
currNode->next=newNode;
}
void insertAnyPosition(int position,int v)
{
Node *currNode=Head;
for(int i=1;i<position;i++)
{
currNode=currNode->next;
}
Node *newNode=createNewNode(v);
newNode->next=currNode->next;
currNode->next=newNode;
}
void delete_First()
{
Node *currNode=Head;
Head=currNode->next;
delete currNode;
}
void delete_Last()
{
Node *currNode=Head;
while(currNode->next->next!=NULL)
{
currNode=currNode->next;
}
Node *myNode=currNode->next;
delete myNode;
currNode->next=NULL;
}
void deleteAnyposition(int position)
{
Node *currNode=Head;
for(int i=1;i<position;i++)
{
currNode=currNode->next;
}
Node *newNode=currNode->next;
currNode->next=currNode->next->next;
delete newNode;
}
int main()
{
createList(4);
cout<<"The create List:"<<endl;
show();
cout<<"\nInsert First:"<<endl;
insertfirst(0);
show();
cout<<"\nInsert any position:"<<endl;
insertAnyPosition(2,11);
show();
cout<<"\nInsert Last:"<<endl;
insertLast(6);
show();
cout<<"\nDelete from First:"<<endl;
delete_First();
show();
cout<<"\nDelete from Any position:"<<endl;
deleteAnyposition(2); //2 is position
show();
cout<<"\nDelete from Last:"<<endl;
delete_Last();
show();
return 0;
}
Excellent info on linked list. Thanks admin for the wonderful post
ReplyDeleteGerman Classes in Chennai
Big Data Training in Chennai
Android Training in Chennai
Selenium Training in Chennai
Digital Marketing Training in Chennai
Hadoop Training in Chennai
Hadoop Training in Velachery