#include<bits/stdc++.h>
using namespace std;
struct Node{
int val;
Node*next;
};
Node*InsertAtBegin(Node*root,int x)
{
Node*newnode=new Node();
newnode->next=NULL;
newnode->val=x;
if(root==NULL)
{
root=newnode;
return root;
}
else
{
newnode->next=root;
root=newnode;
return root;
}
}
Node*InsertAtPos(Node*root,int x,int pos)
{
if(pos==0)
{
root=InsertAtBegin(root,x);
}
else
{
Node*newnode=new Node();
newnode->next=NULL;
newnode->val=x;
Node*currnode;
currnode=root;
for(int i=1;i<pos;i++)
{
currnode=currnode->next;
}
newnode->next=currnode->next;
currnode->next=newnode;
}
return root;
}
Node*InsertAtEnd(Node*root,int x)
{
Node*newnode;
newnode->next=NULL;
newnode->val=x;
if(root==NULL)
{
root=newnode;
return root;
}
Node*currnode;
currnode=root;
while(currnode->next!=NULL)
{
currnode=currnode->next;
}
currnode->next=newnode;
return root;
}
Node*SortedInsert(Node*root,int x)
{
Node*newnode=new Node();
newnode->next=NULL;
newnode->val=x;
Node*currnode,*prevnode;
currnode=root;
prevnode=NULL;
if(root==NULL)
{
root=newnode;
return root;
}
if(x<root->val)
{
newnode->next=root;
root=newnode;
return root;
}
while(currnode!=NULL)
{
if(currnode->val<x)
{
prevnode=currnode;
currnode=currnode->next;
}
else
{
prevnode->next=newnode;
newnode->next=currnode;
return root;
}
}
prevnode->next=newnode;
newnode->next=NULL;
return root;
}
void Print(Node*root)
{
Node*currnode;
currnode=root;
while(currnode!=NULL)
{
cout<<currnode->val<<" ";
currnode=currnode->next;
}
cout<<endl;
}
int main()
{
Node*root=NULL;
root=InsertAtBegin(root,3);
root=InsertAtBegin(root,1);
root=InsertAtBegin(root,9);
Print(root);
root=InsertAtPos(root,2,0);
root=InsertAtPos(root,8,2);
Print(root);
root=InsertAtEnd(root,7);
Print(root);
root=InsertAtEnd(root,5);
Print(root);
root=SortedInsert(root,6);
root=SortedInsert(root,0);
Print(root);
}
I2luY2x1ZGU8Yml0cy9zdGRjKysuaD4KdXNpbmcgbmFtZXNwYWN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