Solved programming problem

Sorted insert 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;

int flag=1;

void insert_node()

{

    node *new_node,*last;

    int n;

    cout<<"Data: ";

    cin>>n;

    new_node=new node();

    new_node->data=n;

    new_node->next=NULL;

    if(head==NULL || head->data >= n) ///check for the 1st node

    {

        new_node->next=head;

        head=new_node;

    }

    else

    {

        last = head;

        while(last->next != NULL && last->next->data<n) ///find the last largest from n

        {

            last=last->next;

        }

        new_node->next=last->next;

        last->next=new_node;

    }

}

void print_node()

{

    node *temp=head;

    cout<<"Your Linked List: "<<endl;

    while(temp!=NULL) ///print node

    {

        cout<<temp->data<<" ";

        temp=temp->next;

    }

    cout<<endl;

}

void menu()

{

    int n;

    cout<<"Press 1 to Insert
Press 2 To Print
Press 3 To Exit"<<endl;

    cin>>n;

    if(n==1)

    {

        insert_node();

    }

    else if(n==2)

    {

        print_node();

    }

    else

    {

        flag=0;

        return;

    }

}

int main()

{

    while(flag==1)

    {

        menu();

    }

    return 0;

}

Output

Press 1 to Insert
Press 2 To Print
Press 3 To Exit
1
Data: 2
Press 1 to Insert
Press 2 To Print
Press 3 To Exit
1
Data: 3
Press 1 to Insert
Press 2 To Print
Press 3 To Exit
1
Data: 1
Press 1 to Insert
Press 2 To Print
Press 3 To Exit
2
Your Linked List:
1 2 3
Press 1 to Insert
Press 2 To Print
Press 3 To Exit
3

 

Join the discussion

Add your comment