Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<bits/stdc++.h>
- using namespace std;
- class Node{
- public:
- int data;
- Node *next;
- };
- class LinkList{
- Node *last = NULL;
- public:
- void add_to_first(int value){
- if(last != NULL)
- return;
- last = new Node();
- last->data = value;
- last->next = last;
- }
- void add_begin(int x){
- if(last == NULL)
- {
- return add_to_first(x);
- }
- Node *newNode = new Node();
- newNode->data = x;
- newNode->next = last->next;
- last->next = newNode;
- }
- void add_end(int x){
- if(last == NULL)
- {
- return add_to_first(x);
- }
- Node *newNode = new Node();
- newNode->data = x;
- newNode->next = last->next;
- last->next = newNode;
- last = newNode;
- }
- void add_after(int x,int value)
- {
- if(last == NULL)
- {
- cout<<"Link list is empty";
- return ;
- }
- Node *newNode,*head;
- head = last->next;
- do{
- if(head->data == value)
- {
- newNode = new Node();
- newNode->data = x;
- newNode->next = head->next;
- head->next = newNode;
- if(head == last)
- last = newNode;
- return ;
- }
- head = head->next;
- }while(head != last->next);
- cout<<value<<" not present in the list."<<endl;
- }
- void delete_Node(int key)
- {
- if(last == NULL)
- return ;
- //Node *curr = last-next, *prev;
- Node *curr , *prev;
- curr = last->next;
- while(curr->data != key)
- {
- if(curr->next == last->next)
- {
- cout<<"Given node id not found"<<endl;
- //break;
- return ;
- }
- prev = curr;
- curr = curr->next;
- }
- if(curr->next == last->next)
- {
- last = NULL;
- delete(curr);
- return ;
- }
- if( curr == last->next)
- {
- prev = last->next;
- // while( prev->next != last->next)
- // {
- // prev = prev->next;
- // }
- last->next = curr->next;
- prev->next = last->next;
- delete(curr);
- }
- else if( curr->next == last->next)
- {
- prev->next = last->next;
- delete(curr);
- }
- else
- {
- prev->next = curr->next;
- delete(curr);
- }
- }
- void display(){
- Node *temp;
- if(last == NULL){
- cout<<"Link List is Empty."<<endl;
- return ;
- }
- temp = last->next;
- do{
- cout<< temp->data<<" ";
- temp = temp->next;
- }while(temp != last->next);
- }
- };
- int main(){
- LinkList ll;
- ll.add_to_first(20);
- ll.add_begin(10);
- ll.add_end(30);
- ll.add_after(500,20);
- ll.delete_Node(500);
- ll.display();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement