Solved programming problem

Delete Last Node and Add it First in single Linked List in C++.

Source code

#include <iostream>

using namespace std;

struct list

{

    int data;

    struct list *next;

};

typedef struct list node;

node *head=NULL;

void insert_node()

{

    node *temp= new node();

    node *last;

    cout<<"Data: ";

    cin>>temp->data;

    temp->next= NULL;

    if(head==NULL)

    {

        head=temp;

    }

    else

    {

        last=head;

        while(last->next!=NULL)

        {

            last =last->next;

        }

        last->next =temp;

    }

}

void last_to_first()

{

    node *temp=head;

    node *first,*prev;

    int value;

    while(temp->next != NULL)

    {

        prev = temp; ///find the last previous

        temp = temp->next;

    }

    value = temp->data; ///save last value

    prev->next = NULL;  ///make last value previous next as NULL

    first = new node();

    ///save the new node as head;

    first->data = value;

    first->next = head;

    head = first;

    delete(temp);

}

void print_node()

{

    node *last= head;

    if(head==NULL)

    {

        cout<<"
No Data Found
";

        return;

    }

    while(last!=NULL)

    {

        cout<<last->data<<" ";

        last= last->next;

    }

}

int main()

{

    int flag;

    do

    {

        cout<<"Press 1 to Insert Node: ";

        cin>>flag;

        if(flag!=1)break;

        insert_node();

    }

    while(flag==1);

    cout<<"
Before: ";

    print_node();

    cout<<"
After: ";

    last_to_first();

    print_node();

    cout<<endl;

    return 0;

}

Output

Press 1 to Insert Node: 1
Data: 1
Press 1 to Insert Node: 1
Data: 2
Press 1 to Insert Node: 1
Data: 3
Press 1 to Insert Node: 1
Data: 4
Press 1 to Insert Node: 1
Data: 5
Press 1 to Insert Node: 0

Before: 1 2 3 4 5
After: 5 1 2 3 4

Join the discussion

Add your comment