Advertisement
Guest User

Narutofication of Single Linked List

a guest
Nov 21st, 2014
136
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.74 KB | None | 0 0
  1. //Creating a Singly linked list and creating a naruto, i.e., a whirlpool of data (First->Last; Last->Second; Second->Second-last; Second-last->Third and so on).
  2. #include <iostream>
  3.  
  4. using namespace std;
  5. class node{
  6.     public:
  7.     node(){
  8.         next=0;
  9.     }
  10.     node(int info, node *ptr=0){
  11.         data=info;
  12.         next=ptr;
  13.     }
  14.     int data;
  15.     node *next;
  16. };
  17.  
  18. class List{
  19.     private:
  20.     node *head, *tail;
  21.  
  22.     public:
  23.     List(){
  24.         head=tail=0;
  25.     }
  26.  
  27.     void addTail(int info){
  28.         if(tail==0){
  29.             tail=head=new node(info,head);
  30.         }else{
  31.             tail->next=new node(info);
  32.             tail=tail->next;
  33.         }
  34.     }
  35.  
  36.     void listAll(){
  37.         if(head==0){
  38.             cout<<"\n\nList is empty!\n\n";
  39.         }else{
  40.             for(node *tmp=head; !(tmp==0); tmp=tmp->next){
  41.                 cout<<tmp->data<<"\t";
  42.             }
  43.         }
  44.     }
  45.  
  46.     void naruto(){
  47.         node *h,*origHead=head,*t=tail;
  48.         while(head!=tail){
  49.             h=head->next;
  50.             head->next=tail;
  51.             head=h;
  52.             tail->next=head;
  53.             if(head->next==tail){
  54.                 tail=head;
  55.                 break;
  56.             }
  57.             while(h->next!=tail){
  58.                 h=h->next;
  59.                 t=h;
  60.             }
  61.             tail=t;
  62.             h=head;
  63.         }
  64.         head=origHead;
  65.         tail->next=0;
  66.     }
  67. };
  68. int main(){
  69.  
  70.     List l;
  71.     int length,in;
  72.     cout<<"Enter number of nodes: ";
  73.     cin>>length;
  74.  
  75.     for(int i=0;i<length;i++){
  76.         cout<<"\n\nEnter data: ";
  77.         cin>>in;
  78.         l.addTail(in);
  79.     }
  80.     l.listAll();
  81.  
  82.     cout<<"\n\nAfter narutofying:\n";
  83.     l.naruto();
  84.     l.listAll();
  85.     return 0;
  86. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement