Advertisement
Haval1

Basic operation in Linked List

Mar 23rd, 2019
191
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.91 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. using namespace std;
  4. struct node
  5. {
  6.     char data;
  7.     node *next;
  8. };
  9. void createList(node *&head, node *&tail, char item)
  10. {
  11.     node *newNode = new node;
  12.     newNode->data = item;
  13.     newNode->next = NULL;
  14.     if(head == NULL)
  15.         head = tail = newNode;
  16.     else
  17.     {
  18.         tail->next = newNode;
  19.         tail = newNode;
  20.     }
  21. }
  22. void display(node *&head)
  23. {
  24.     node *temp;
  25.     temp = head;
  26.     while(temp != NULL)
  27.     {
  28.         cout<<"data is : "<<temp->data<<endl;
  29.         temp = temp->next;
  30.     }
  31. }
  32.  
  33. int delete4th(node *&head)
  34. {
  35.     node *temp = new node;
  36.     node *curr = new node;
  37.     curr = temp = head;
  38.     int itempos = 0,pos = 4;
  39.     if(head == NULL){
  40.         cout<<"Add some element \n";
  41.         return 0;
  42.     }
  43.     while(head != NULL || itempos != pos)
  44.     {
  45.         temp = head;
  46.         head = head->next;
  47.         itempos++;
  48.     }
  49.     cout<<"data : "<<temp->data<<endl;
  50. }
  51.  
  52. int main()
  53. {
  54.     node *head,*tail;
  55.     tail = head = NULL;
  56.     int choice,i;
  57.     char item;
  58.     do
  59.     {
  60.         cout<<"1- create list \n";
  61.         cout<<"2- add at the end\n";
  62.         cout<<"3- display the list\n";
  63.         cout<<"4- delete 4th element\n";
  64.         cout<<"5- exit\n";
  65.         cout<<"Enter your choice : ";
  66.         cin>>choice;
  67.         switch(choice)
  68.         {
  69.         case 1:
  70.             for(i=0;i<10;i++)
  71.             {
  72.                 cout<<"Enter data (char) : ";
  73.                 cin>>item;
  74.                 createList(head,tail,item);
  75.             }
  76.             break;
  77.         case 2:
  78.             cout<<"Enter the element (char) : ";
  79.             cin>>item;
  80.             createList(head,tail,item);
  81.             break;
  82.         case 3:
  83.             display(head);
  84.             break;
  85.         case 4:
  86.             delete4th(head);
  87.             break;
  88.         default:
  89.             break;
  90.         }
  91.     }while(choice != 5);
  92.     return 0;
  93. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement