Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<bits/stdc++.h>
- using namespace std;
- struct node
- {
- int data;
- struct node *next;
- struct node *prev;
- };
- typedef struct node Node;
- Node* create_node(int item, Node *next,Node*prev)
- {
- Node* new_node=new Node();
- if(new_node==NULL)
- cout<<"Error"<<endl;
- else
- {
- new_node->data=item;
- new_node->next=next;
- new_node->prev=prev;
- }
- return new_node;
- }
- Node* prepend(int item,Node* head)
- {
- Node* new_node=create_node(item,head,NULL);
- return new_node;
- }
- Node* append(int item,Node *head)
- {
- Node *new_node=create_node(item,NULL,NULL);
- if(head==NULL)
- return new_node;
- else
- {
- Node* current=new Node();
- current=head;
- while(current->next!=NULL)
- current=current->next;
- current->next=new_node;
- new_node->prev=current;
- }
- return head;
- }
- Node* insertn(int item,Node* head,int key)
- {
- Node* new_node=create_node(item,NULL,NULL);
- if(head==NULL)
- cout<<"Error"<<endl;
- else
- {
- Node *current=new Node();
- current=head;
- while(current!=NULL&¤t->data!=key)
- current=current->next;
- if(current!=NULL)
- {
- new_node->next=current->next;
- current->next=new_node;
- new_node->prev=current;
- }
- else
- cout<<"Value not found"<<endl;
- }
- return head;
- }
- void display(Node *head)
- {
- cout<<"Linked list:"<<endl;
- while(head!=NULL)
- {
- cout<<head->data<<" ";
- head=head->next;
- }
- cout<<endl;
- }
- int main()
- {
- Node*head=NULL;
- int t;
- cout<<"Number of test cases"<<endl;
- cin>>t;
- for(int i=0; i<t; i++)
- {
- cout<<"Enter 1 to prepend, 2 to append and 3 to insert"<<endl;
- int n;
- cin>>n;
- cout<<"Enter the value"<<endl;
- int item;
- cin>>item;
- if(n==1)
- {
- head=prepend(item,head);
- display(head);
- }
- else if(n==2)
- {
- head=append(item,head);
- display(head);
- }
- else if(n==3)
- {
- cout<<"Enter the key"<<endl;
- int key;
- cin>>key;
- head=insertn(item,head,key);
- display(head);
- }
- }
- }
Add Comment
Please, Sign In to add comment