Reverse single linked list

 

Reverse single linked list






OURSHOPKEEPER










#include <iostream>
#include <cstdlib>
using namespace std;

//reverse linked list
struct node
{
    int data;
    struct node *next;
};

void display();
void insertion();
int length();
void reverse();

struct node *head = NULL;

int main()
{
    int choice;
    while (1)
    {
        cout << "1.Insertion \n2. reverse \n3.display \n4.length \n5.exit\n";
        cout << "Enter the choice : ";
        cin >> choice;

        switch (choice)
        {
        case 1:
            insertion();
            break;
        case 2:
            reverse();
            break;
        case 3:
            display();
            break;
        case 4:
            cout << length();
            break;
        case 5:
            exit(0);
        default:
            cout << "Invalid" << endl;
        }
    }
    return 0;
}

void display()
{
    struct node *temp;
    temp = head;
    if (head == NULL)
    {
        head = temp;
        cout << "Linked list is empty \n"
             << endl;
    }
    else
        while (temp != NULL)
        {
            cout << temp->data << "->";
            temp = temp->next;
        }
    cout << "\n\n";
}

void insertion()
{
    int data, i = 0;
    int len = length();
    struct node *temp, *p;

    temp = (struct node *)malloc(sizeof(struct node));
    cout << "Enter the data: ";
    cin >> data;
    temp->data = data;
    temp->next = NULL;
    p = head;

    if (head == NULL)
    {
        head = temp;
        cout << "Node is Inserted Success Fully \n"
             << endl;
    }
    else
    {
        while (i < len - 1)
        {
            p = p->next;
            i++;
        }
        p->next = temp;
        cout << "Node inserted successfully\n"
             << endl;
    }
}

int length()
{
    int length = 0;
    struct node *temp;
    temp = head;

    while (temp != NULL)
    {
        length++;
        temp = temp->next;
    }
    return length;
    cout << "\n";
}

void reverse()
{
    struct node *current = head;
    struct node *prev = NULL, *after = NULL;
    while (current != NULL)
    {
        after = current->next;
        current->next = prev;
        prev = current;
        current = after;
    }
    head = prev;
    cout << "reverse successful \n\n";
}







    


Click on the above button to download the code.



Post a Comment

If you have furthur QUERIES please let us know

Previous Post Next Post