Website Summary Files Commits Branches @commit @diff @stats
path: root / Additional / Additional-2023-SI / MergeIntoList.cpp
blob: 7d575aaab27eec9339ace806ed1384723c5b4130 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
#include <iostream>

struct ListNode
{
    int val;
    ListNode *next;
    ListNode(int x, ListNode *n = nullptr) : val(x), next(n) {}
};

ListNode *advance(ListNode *from, size_t index)
{
    while (index)
    {
        if (from == nullptr)
        {
            return nullptr;
        }

        from = from->next;
        --index;
    }

    return from;
}

ListNode *getTail(ListNode *list)
{
    if (!list || !list->next)
    {
        return list;
    }

    while (list->next)
    {
        list = list->next;
    }
    return list;
}

void freeRagne(ListNode *from, ListNode *to)
{
    while (from != to)
    {
        ListNode *node = from;
        from = from->next;
        delete node;
    }
}

void free(ListNode *ll)
{
    while (ll)
    {
        ListNode *toDelete = ll;
        ll = ll->next;
        delete toDelete;
    }
}

ListNode *addFront(ListNode *destination, ListNode *target, size_t to)
{
    ListNode *tail = getTail(target);
    ListNode *end = advance(destination, to + 1);
    tail->next = end;
    freeRagne(destination, end);
    return target;
}

ListNode *mergeInBetween(ListNode *destination, ListNode *target, size_t from, size_t to)
{
    if (from == 0)
    {
        return addFront(destination, target, to);
    }

    ListNode *predBegin = advance(destination, from - 1);
    if (!predBegin)
    {
        return nullptr;
    }

    ListNode *postEnd = advance(predBegin, to - from + 2);
    ListNode *toDeleteHolder = predBegin->next;
    ListNode *targetTail = getTail(target);

    predBegin->next = target;
    targetTail->next = postEnd;

    freeRagne(toDeleteHolder, postEnd);

    return destination;
}

int main()
{
    ListNode *fst = new ListNode(1,
                                 new ListNode(2,
                                              new ListNode(3,
                                                           new ListNode(4,
                                                                        new ListNode(6)))));

    ListNode *snd = new ListNode(3,
                                 new ListNode(4, 
                                    new ListNode(5)));

    ListNode *ans = mergeInBetween(fst, snd, 1, 3);

    ListNode *it = ans;

    while(it)
    {
        std::cout << it->val << " ";
        it = it->next;
    }

    free(ans);
}