#include <iostream>
using namespace std;
class node {
public:
int data;
node*next;
node(int d) {
data=d;
next=NULL;
}
};
void insertAthead( node*&head,int d) {
if(head==NULL) {
head=new node(d);
return;
}
node *n=new node(d);
n->next=head;
head=n;
}
int length(node*head) {
int cnt=0;
while(head!=NULL) {
cnt++;
head=head->next;
}
return cnt;
}
void insertAtTail(node * &head ,int d) {
if(head==NULL) {
insertAthead(head,d);
return;
}
node *tail=head;
while(tail->next!=NULL) {
tail=tail->next;
}
tail->next=new node(d);
return;
}
void insertInMiddle(node* &head ,int d,int p) {
if(head==NULL or p==0) {
insertAthead(head,d);
return;
}
else if(p>length(head)) {
insertAtTail(head,d);
}
else {
int jump=1;
node *temp=head;
while(jump<=p-1) {
temp=temp->next;
jump++;
}
node *n=new node(d);
n->next=temp->next;
temp->next=n;
}
}
void print(node*head) {
while(head!=NULL) {
cout<<head->data<<"->";
head=head->next;
}
cout<<endl;
}
void deleteHead(node * &head) {
if(head==NULL) {
return;
}
node *temp=head->next;
delete head;
head=temp;
}
void deleteit(node*&head,int p)
{
if(p==1) {
deleteHead(head);
}
else {
int j =1;
node *temp=head;
node *prev=head;
node *midd=head;
while(j<=p-1)
{
prev=temp;
temp=temp->next;
midd=temp;
j++;
}
temp=temp->next;
prev->next=temp;
delete midd;
}
//midd=temp;
//temp=temp->next;
}
void deleteTail(node *head) {
if(head==NULL) {
return;
}
node *prev;
while(head->next!=NULL) {
prev=head;
head=head->next;
}
prev->next=NULL;
delete head;
}
bool Search(node *head ,int d) {
node *temp=head;
while(head!=NULL) {
if(head->data==d) {
return true;
}
head=head->next;
}
return false;
}
//recursively
bool rsearch(node *head ,int key) {
if(head==NULL) {
return false;
}
if(head->data==key) {
return true;
}
else {
return rsearch(head->next,key);
}
}
node* take_input() {
int d;
cin>>d;
node * head=NULL;
while(d!=-1) {
insertAthead(head,d);
cin>>d;
}
return head;
}
node* take_input_file() {
int d;
node *head=NULL;
while(cin>>d) {
insertAthead(head,d);
cin>>d;
}
return head;
}
int main() {
//node*head=NULL;
/* insertAthead(head,3);
insertAthead(head,2);
insertAthead(head,1);
insertAthead(head,0);
print(head);
cout<<endl;
insertInMiddle(head,4,4);
insertAtTail(head,9);
deleteHead(head);
insertAtTail(head,10);
print(head);
deleteit(head,2);
deleteit(head,1);
insertAtTail(head,11);
deleteit(head,5);
deleteTail(head);
insertAthead(head,99);
print(head);
cout<<"___________"<<endl;
int d;
cin>>d;
if(Search(head,d)) {
cout<<"found"<<endl;
}
else {
cout<<"not found"<<endl;
}
*/
node *head=take_input_file();
print(head);
return 0;
}
1
33
222
4444
5555
66666