Solved programming problem

If The Sum of Two Consecutive nodes is more then 10,then insert a node with data -10 between them i

Source code

#include <iostream>

using namespace std;

struct list

{

    int data;

    struct list *next;

};

typedef struct list node;

node *head;

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  print_node()

{

    node *temp = head;

    if(head== NULL)

    {

        cout<<"
No Data Found "<<endl;

        return;

    }

    else

    {

        while(temp != NULL)

        {

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

            temp = temp->next;

        }

    }

}

void add_10()

{

    node *temp=head,*prev=head;

    while(temp->next!=NULL)

    {

        prev = temp;

        if((temp->data + temp->next->data) > 10) ///check the sum

        {

            node *new_node= new node(); ///create a new node add save -10

            new_node->data =-10;

            new_node->next=prev->next; ///liked to next element

            prev->next = new_node; ///linked with new node

        }

        temp = temp->next;

    }

}

int main()

{

    int flag;

    do

    {

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

        cin>>flag;

        if(flag!=1) break;

        insert_node();

    }

    while(flag==1);

    cout<<"
Linked List:  " ;

    print_node();

    cout<<"
New Linked LIst: ";

    add_10();

    print_node();

    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: 8
Press 1 to Insert Node: 1
data: 9
Press 1 to Insert Node: 0

Linked List:  1 2 3 4 8 9
New Linked LIst: 1 2 3 4 -10 8 -10 9

Join the discussion

Add your comment