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

Top comments (0)