DEV Community

Mujahida Joynab
Mujahida Joynab

Posted on

List Problem

Question: You have a doubly linked list which is empty initially. You need to take a value Q which refers to queries. For each query you will be given X and V. You will insert the value V to the Xth index of the doubly linked list and print the list in both left to right and right to left. If the index is invalid then print “Invalid”.

Sample Input
6
0 10
1 20
4 30
0 30
1 40
5 50
Sample Output

10
10
10 20
20 10
Invalid
30 10 20
20 10 30
30 40 10 20
20 10 40 30
Invalid

#include <bits/stdc++.h>
using namespace std;

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    int val;
    list<int> lst;

    int t;
    cin >> t;
    while (t--)
    {
        int x, v;
        cin >> x >> v;
        if (x > lst.size())
        {
            cout << "Invalid\n";
            continue;
        }

        else if (x == lst.size())
        {
            lst.push_back(v);
        }
        else if (x == 0)
        {
            lst.push_front(v);
        }
        else
        {
            lst.insert(next(lst.begin(), x), v);
        }
        for (int num : lst)
        {
            cout << num << " ";
        }
        cout << endl;
        lst.reverse();

        for (int num : lst)
        {
            cout << num << " ";
        }
        cout << endl;
        lst.reverse();
    }
}
Enter fullscreen mode Exit fullscreen mode

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay