Solved programming problem

Linked List octopus in C++.

Source code

#include <bits/stdc++.h>

using namespace std;

struct node

{

    int data;

    struct node* next;

};

struct octopus

{

    struct node* l;

    struct node* r;

    struct node* t;

    struct node* b;

};

struct octopus* head = new octopus;

void max_sum()

{

    int l = 0, r = 0, t = 0, b = 0;

    struct node* it = head->l;

    while(it != NULL)

    {

        l = l + it->data;

        it = it->next;

    }

    it = head->r;

    while(it != NULL)

    {

        r = r + it->data;

        it = it->next;

    }

    it = head->t;

    while(it != NULL)

    {

        t = t + it->data;

        it = it->next;

    }

    it = head->b;

    while(it != NULL)

    {

        b = b + it->data;

        it = it->next;

    }

    if(l >= r && l >= t && l >= b)

    {

        cout << "Left is max " << l << endl;

    }

    else if(r >= l && r >= t && r >= b)

    {

        cout << "Right is max " << r << endl;

    }

    else if(t >= l && t >= r && t >= b)

    {

        cout << "Top is max " << t << endl;

    }

    else

    {

        cout << "Bottom  is max " << b << endl;

    }

}

int main()

{

    head->l = NULL;

    head->r = NULL;

    head->t = NULL;

    head->b = NULL;

    int v, t;

    char c;

    cin >> t;

    while(t --)

    {

        cin >> c >> v;

        struct node* tem;

        tem = new node;

        tem->data = v;

        tem->next = NULL;

        if(c == 'L')

        {

            if(head->l == NULL)

            {

                head->l = tem;

            }

            else

            {

                tem->next = head->l;

                head->l = tem;

            }

        }

        if(c == 'R')

        {

            if(head->r == NULL)

            {

                head->r = tem;

            }

            else

            {

                tem->next = head->r;

                head->r = tem;

            }

        }

        if(c == 'T')

        {

            if(head->t == NULL)

            {

                head->t = tem;

            }

            else

            {

                tem->next = head->t;

                head->t = tem;

            }

        }

        if(c == 'B')

        {

            if(head->b == NULL)

            {

                head->b = tem;

            }

            else

            {

                tem->next = head->b;

                head->b = tem;

            }

        }

    }

    max_sum();

    return 0;

}

Output

5
R 3
L 1
R 2

T 8
B 0
Top is max 8

Join the discussion

Add your comment