Website Summary Files Commits Branches @commit @diff @stats
path: root / Additional / Additional-2024-IS / solutions / remove-nodes-recursion.cpp
blob: bff2191ed6b12d101f7142aa8b8936344f2da8a8 (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
#include <climits>
#include <iostream>

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

class Solution
{
  public:
	ListNode* removeNodes(ListNode* head)
	{
		int maxVal = INT_MIN;
		return removeNodesRecursive(head, maxVal);
	}

  private:
	ListNode* removeNodesRecursive(ListNode* node, int& maxVal)
	{
		if (node == nullptr)
		{
			return nullptr;
		}

		ListNode* filteredNext = removeNodesRecursive(node->next, maxVal);

		if (node->val >= maxVal)
		{
			maxVal = node->val;
			node->next = filteredNext;
			return node;
		}
		else
		{
			delete node;
			return filteredNext;
		}
	}
};

void printList(ListNode* node)
{
	while (node)
	{
		std::cout << node->val << " ";
		node = node->next;
	}
	std::cout << std::endl;
}

int main()
{
	Solution s;

	ListNode* result =
		s.removeNodes(new ListNode(5, new ListNode(2, new ListNode(13, new ListNode(3, new ListNode(8))))));

	printList(result);

	ListNode* current = result;
	while (current)
	{
		ListNode* temp = current;
		current = current->next;
		delete temp;
	}

	return 0;
}