Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<iostream>
- using namespace std;
- struct node
- {
- int data;
- node *next;
- };
- class Linked_List
- {
- private:
- node *head, *tail;
- public:
- Linked_List()
- {
- head=NULL;
- tail=NULL;
- }
- ///Function to add data in the last of the list
- void add_last(int n)
- {
- node *tmp = new node; //allocates a new node
- tmp->data = n;
- tmp->next = NULL;
- if(head == NULL)
- {
- head = tmp;
- tail = tmp;
- }
- else
- {
- tail->next=tmp;
- tail = tail->next;
- }
- }
- node* gethead()
- {
- return head;
- }
- void display()
- {
- node *tmp;
- tmp=head;
- while(tmp!=NULL)
- {
- cout<< tmp->data <<" ";
- tmp=tmp->next;
- }
- cout<<endl;
- }
- void add_by_index(node *a, int n,int pos)
- {
- //beginning
- if(pos==0)
- {
- node *tmp = new node;
- tmp -> data = n;
- tmp -> next = head;
- head = tmp;
- }
- //Middle or last by indexing
- else
- {
- int i=0;
- node *tmp;
- tmp=a;
- while(i!=pos)
- {
- if(i==(pos-1))
- {
- node* newNode = new node;
- newNode->data = n;
- newNode->next = tmp->next;
- tmp->next = newNode;
- }
- tmp=tmp->next;
- i++;
- }
- }
- }
- //Deleting Node
- void del (node *before_del)
- {
- node* temp;
- temp = before_del->next;
- before_del->next = temp->next;
- delete temp;
- }
- void delete_position(int pos)
- {
- pos=pos+1;
- int i;
- //beginning
- if(pos==1)
- {
- node *temp=new node;
- temp=head;
- head=head->next;
- delete temp;
- }
- //middle or last
- else
- {
- node *current=new node;
- node *previous=new node;
- current=head;
- for(i=1;i<pos;i++)
- {
- previous=current;
- current=current->next;
- }
- previous->next=current->next;
- }
- }
- };
- int main()
- {
- Linked_List a;
- a.add_last(5);
- a.add_last(12);
- a.add_last(32);
- a.add_last(43);
- a.add_last(87);
- a.add_last(85);
- a.add_last(39);
- a.add_last(98);
- a.display();
- a.add_by_index(a.gethead(),777,1);
- a.display();
- a.add_by_index(a.gethead(),999,3);
- a.display();
- a.add_by_index(a.gethead(),222,0);
- a.display();
- a.add_by_index(a.gethead(),1111,11);
- a.display();
- // a.add_by_index(a.gethead(),13333,13);
- // a.display();
- a.delete_position(3);
- a.display();
- a.delete_position(2);
- a.display();
- a.delete_position(1);
- a.display();
- a.delete_position(9);
- a.display();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement