Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //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).
- #include <iostream>
- using namespace std;
- class node{
- public:
- node(){
- next=0;
- }
- node(int info, node *ptr=0){
- data=info;
- next=ptr;
- }
- int data;
- node *next;
- };
- class List{
- private:
- node *head, *tail;
- public:
- List(){
- head=tail=0;
- }
- void addTail(int info){
- if(tail==0){
- tail=head=new node(info,head);
- }else{
- tail->next=new node(info);
- tail=tail->next;
- }
- }
- void listAll(){
- if(head==0){
- cout<<"\n\nList is empty!\n\n";
- }else{
- for(node *tmp=head; !(tmp==0); tmp=tmp->next){
- cout<<tmp->data<<"\t";
- }
- }
- }
- void naruto(){
- node *h,*origHead=head,*t=tail;
- while(head!=tail){
- h=head->next;
- head->next=tail;
- head=h;
- tail->next=head;
- if(head->next==tail){
- tail=head;
- break;
- }
- while(h->next!=tail){
- h=h->next;
- t=h;
- }
- tail=t;
- h=head;
- }
- head=origHead;
- tail->next=0;
- }
- };
- int main(){
- List l;
- int length,in;
- cout<<"Enter number of nodes: ";
- cin>>length;
- for(int i=0;i<length;i++){
- cout<<"\n\nEnter data: ";
- cin>>in;
- l.addTail(in);
- }
- l.listAll();
- cout<<"\n\nAfter narutofying:\n";
- l.naruto();
- l.listAll();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement