Aleph-w 3.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
linear_structures_example.C
Go to the documentation of this file.
1
2/*
3 Aleph_w
4
5 Data structures & Algorithms
6 version 2.0.0b
7 https://github.com/lrleon/Aleph-w
8
9 This file is part of Aleph-w library
10
11 Copyright (c) 2002-2026 Leandro Rabindranath Leon
12
13 Permission is hereby granted, free of charge, to any person obtaining a copy
14 of this software and associated documentation files (the "Software"), to deal
15 in the Software without restriction, including without limitation the rights
16 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
17 copies of the Software, and to permit persons to whom the Software is
18 furnished to do so, subject to the following conditions:
19
20 The above copyright notice and this permission notice shall be included in all
21 copies or substantial portions of the Software.
22
23 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
24 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
25 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
26 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
27 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
28 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
29 SOFTWARE.
30*/
31
32
192#include <iostream>
193#include <string>
194#include <tpl_dynListStack.H>
195#include <tpl_dynListQueue.H>
196#include <tpl_dynArray.H>
197#include <tpl_dynList.H>
198#include <tpl_dynDlist.H>
199#include <tpl_arrayStack.H>
200#include <tpl_arrayQueue.H>
201
202using namespace std;
203using namespace Aleph;
204
205// =============================================================================
206// Example 1: Stack (LIFO)
207// =============================================================================
208
210{
211 cout << "\n";
212 cout << "╔══════════════════════════════════════════════════════════════════╗\n";
213 cout << "║ EXAMPLE 1: Stack (LIFO - Last In First Out) ║\n";
214 cout << "╚══════════════════════════════════════════════════════════════════╝\n\n";
215
216 cout << "Stack follows LIFO principle: last element pushed is first popped.\n\n";
217
218 // Dynamic stack (unlimited size)
220
221 cout << "--- DynListStack operations ---\n\n";
222
223 // Push elements
224 cout << "Pushing: Apple, Banana, Cherry, Date\n";
225 stack.push("Apple");
226 stack.push("Banana");
227 stack.push("Cherry");
228 stack.push("Date");
229
230 cout << "Stack size: " << stack.size() << "\n";
231 cout << "Top element: " << stack.top() << "\n\n";
232
233 // Pop elements
234 cout << "Popping elements (LIFO order):\n";
235 while (!stack.is_empty())
236 cout << " Pop: " << stack.pop() << "\n";
237
238 cout << "\n--- Practical application: Balanced parentheses ---\n\n";
239
240 auto check_balanced = [](const string& expr) {
242 for (char c : expr) {
243 if (c == '(' || c == '[' || c == '{')
244 s.push(c);
245 else if (c == ')' || c == ']' || c == '}') {
246 if (s.is_empty()) return false;
247 char top = s.pop();
248 if ((c == ')' && top != '(') ||
249 (c == ']' && top != '[') ||
250 (c == '}' && top != '{'))
251 return false;
252 }
253 }
254 return s.is_empty();
255 };
256
257 auto test_expr = [&](const string& expr) {
258 cout << " \"" << expr << "\" → "
259 << (check_balanced(expr) ? "BALANCED" : "UNBALANCED") << "\n";
260 };
261
262 test_expr("((a+b)*c)");
263 test_expr("{[a+(b*c)]}");
264 test_expr("((a+b)");
265 test_expr("([a+b)]");
266}
267
268// =============================================================================
269// Example 2: Queue (FIFO)
270// =============================================================================
271
273{
274 cout << "\n";
275 cout << "╔══════════════════════════════════════════════════════════════════╗\n";
276 cout << "║ EXAMPLE 2: Queue (FIFO - First In First Out) ║\n";
277 cout << "╚══════════════════════════════════════════════════════════════════╝\n\n";
278
279 cout << "Queue follows FIFO principle: first element added is first removed.\n\n";
280
282
283 cout << "--- DynListQueue operations ---\n\n";
284
285 // Enqueue elements
286 cout << "Enqueueing: Task1, Task2, Task3, Task4\n";
287 queue.put("Task1");
288 queue.put("Task2");
289 queue.put("Task3");
290 queue.put("Task4");
291
292 cout << "Queue size: " << queue.size() << "\n";
293 cout << "Front element: " << queue.front() << "\n";
294 cout << "Rear element: " << queue.rear() << "\n\n";
295
296 // Dequeue elements
297 cout << "Dequeueing elements (FIFO order):\n";
298 while (!queue.is_empty())
299 cout << " Dequeue: " << queue.get() << "\n";
300
301 cout << "\n--- Practical application: Print job scheduler ---\n\n";
302
303 struct PrintJob {
304 string name;
305 int pages;
306 };
307
309
310 // Add print jobs
311 printer.put({"Report.pdf", 10});
312 printer.put({"Photo.jpg", 1});
313 printer.put({"Manual.pdf", 50});
314 printer.put({"Letter.doc", 2});
315
316 cout << "Print queue:\n";
317 int total_pages = 0;
318 while (!printer.is_empty()) {
320 cout << " Printing: " << job.name << " (" << job.pages << " pages)\n";
321 total_pages += job.pages;
322 }
323 cout << "Total pages printed: " << total_pages << "\n";
324}
325
326// =============================================================================
327// Example 3: Dynamic Array
328// =============================================================================
329
331{
332 cout << "\n";
333 cout << "╔══════════════════════════════════════════════════════════════════╗\n";
334 cout << "║ EXAMPLE 3: DynArray (Resizable Array) ║\n";
335 cout << "╚══════════════════════════════════════════════════════════════════╝\n\n";
336
337 cout << "DynArray provides O(1) random access with dynamic resizing.\n\n";
338
339 DynArray<int> arr;
340
341 cout << "--- Basic operations ---\n\n";
342
343 // Append elements
344 cout << "Appending: 10, 20, 30, 40, 50\n";
345 arr.append(10);
346 arr.append(20);
347 arr.append(30);
348 arr.append(40);
349 arr.append(50);
350
351 cout << "Size: " << arr.size() << "\n";
352 cout << "Elements: ";
353 for (size_t i = 0; i < arr.size(); ++i)
354 cout << arr(i) << " ";
355 cout << "\n\n";
356
357 // Random access
358 cout << "Random access:\n";
359 cout << " arr(0) = " << arr(0) << "\n";
360 cout << " arr(2) = " << arr(2) << "\n";
361 cout << " arr(4) = " << arr(4) << "\n\n";
362
363 // Modify element
364 cout << "Modifying arr(2) = 300\n";
365 arr(2) = 300;
366 cout << "Elements: ";
367 for (size_t i = 0; i < arr.size(); ++i)
368 cout << arr(i) << " ";
369 cout << "\n\n";
370
371 cout << "--- Functional operations ---\n\n";
372
374 for (int i = 1; i <= 10; ++i)
375 numbers.append(i);
376
377 cout << "Original: ";
378 numbers.for_each([](int x) { cout << x << " "; });
379 cout << "\n";
380
381 // Filter even numbers
382 auto evens = numbers.filter([](int x) { return x % 2 == 0; });
383 cout << "Evens: ";
384 evens.for_each([](int x) { cout << x << " "; });
385 cout << "\n";
386
387 // Map: square each number
388 auto squared = numbers.maps<int>([](int x) { return x * x; });
389 cout << "Squared: ";
390 squared.for_each([](int x) { cout << x << " "; });
391 cout << "\n";
392
393 // Fold: sum all numbers
394 int sum = numbers.foldl(0, [](int acc, int x) { return acc + x; });
395 cout << "Sum: " << sum << "\n";
396}
397
398// =============================================================================
399// Example 4: Dynamic Lists
400// =============================================================================
401
403{
404 cout << "\n";
405 cout << "╔══════════════════════════════════════════════════════════════════╗\n";
406 cout << "║ EXAMPLE 4: DynList and DynDlist (Linked Lists) ║\n";
407 cout << "╚══════════════════════════════════════════════════════════════════╝\n\n";
408
409 cout << "Linked lists allow O(1) insertion/deletion at any known position.\n\n";
410
411 // Singly linked list
412 cout << "--- DynList (singly linked) ---\n\n";
413
414 DynList<int> slist;
415
416 // Insert at front (O(1))
417 cout << "Inserting at front: 3, 2, 1\n";
418 slist.insert(3);
419 slist.insert(2);
420 slist.insert(1);
421
422 // Append at end
423 cout << "Appending at end: 4, 5\n";
424 slist.append(4);
425 slist.append(5);
426
427 cout << "List: ";
428 slist.for_each([](int x) { cout << x << " "; });
429 cout << "\n";
430 cout << "Size: " << slist.size() << "\n\n";
431
432 // Doubly linked list
433 cout << "--- DynDlist (doubly linked) ---\n\n";
434
435 DynDlist<string> dlist;
436
437 cout << "Inserting: First, Second, Third\n";
438 dlist.append("First");
439 dlist.append("Second");
440 dlist.append("Third");
441
442 cout << "Forward: ";
443 dlist.for_each([](const string& s) { cout << s << " "; });
444 cout << "\n";
445
446 // Remove from front and back
447 cout << "\nRemoving first: " << dlist.remove_first() << "\n";
448 cout << "Removing last: " << dlist.remove_last() << "\n";
449
450 cout << "Remaining: ";
451 dlist.for_each([](const string& s) { cout << s << " "; });
452 cout << "\n";
453}
454
455// =============================================================================
456// Example 5: Comparison of Stack vs Queue
457// =============================================================================
458
460{
461 cout << "\n";
462 cout << "╔══════════════════════════════════════════════════════════════════╗\n";
463 cout << "║ EXAMPLE 5: Stack vs Queue Comparison ║\n";
464 cout << "╚══════════════════════════════════════════════════════════════════╝\n\n";
465
466 DynListStack<int> stack;
467 DynListQueue<int> queue;
468
469 // Add same elements to both
470 cout << "Adding elements 1, 2, 3, 4, 5 to both structures:\n\n";
471 for (int i = 1; i <= 5; ++i) {
472 stack.push(i);
473 queue.put(i);
474 }
475
476 // Remove and compare order
477 cout << "Removal order:\n";
478 cout << " Stack (LIFO): ";
479 while (!stack.is_empty())
480 cout << stack.pop() << " ";
481 cout << "\n";
482
483 cout << " Queue (FIFO): ";
484 while (!queue.is_empty())
485 cout << queue.get() << " ";
486 cout << "\n";
487
488 cout << "\nUse Stack for: undo/redo, recursion, backtracking\n";
489 cout << "Use Queue for: scheduling, BFS, buffering\n";
490}
491
492// =============================================================================
493// Main
494// =============================================================================
495
496int main()
497{
498 cout << "\n";
499 cout << "╔══════════════════════════════════════════════════════════════════╗\n";
500 cout << "║ Linear Data Structures in Aleph-w Library ║\n";
501 cout << "║ ║\n";
502 cout << "║ Aleph-w Library - https://github.com/lrleon/Aleph-w ║\n";
503 cout << "╚══════════════════════════════════════════════════════════════════╝\n";
504
505 demo_stack();
506 demo_queue();
508 demo_dynlist();
510
511 cout << "\n";
512 cout << "╔══════════════════════════════════════════════════════════════════╗\n";
513 cout << "║ Summary ║\n";
514 cout << "╠══════════════════════════════════════════════════════════════════╣\n";
515 cout << "║ DynListStack: Dynamic LIFO stack (linked list based) ║\n";
516 cout << "║ DynListQueue: Dynamic FIFO queue (circular list based) ║\n";
517 cout << "║ DynArray: Resizable array with O(1) access ║\n";
518 cout << "║ DynList: Singly linked list ║\n";
519 cout << "║ DynDlist: Doubly linked list ║\n";
520 cout << "║ ║\n";
521 cout << "║ All support functional operations: map, filter, fold, for_each ║\n";
522 cout << "╚══════════════════════════════════════════════════════════════════╝\n\n";
523
524 return 0;
525}
size_t size() const noexcept
Return the current dimension of array.
T & append()
Allocate a new entry to the end of array.
Dynamic doubly linked list with O(1) size and bidirectional access.
T remove_last()
Remove the last item of the list; return a copy of removed item.
T & append(const T &item)
Append a copied item at the end of the list.
T remove_first()
Remove the first item of the list; return a copy of removed item.
Dynamic queue of elements of generic type T based on single linked list.
T & put(const T &data)
The type of element.
constexpr size_t size() const noexcept
Return the number of elements.
T get()
Remove the oldest item of the queue.
T & front()
Return a modifiable reference to the oldest item in the queue.
T & rear()
Return a modifiable reference to the youngest item in the queue.
bool is_empty() const noexcept
Return true if this is empty.
Dynamic stack of elements of generic type T based on a singly linked list.
T & top()
Return a modifiable reference to the top item of the stack.
bool is_empty() const noexcept
Check if the stack is empty.
constexpr size_t size() const noexcept
Return the number of elements in the stack.
T pop()
Remove and return the top item of the stack.
T & push(const T &data)
Push an item by copy onto the top of the stack.
Dynamic singly linked list with functional programming support.
Definition htlist.H:1423
T & insert(const T &item)
Insert a new item by copy.
Definition htlist.H:1502
T & append(const T &item)
Append a new item by copy.
Definition htlist.H:1562
T & put(const T &item)
Definition htlist.H:1532
constexpr bool is_empty() const noexcept
Return true if list is empty.
Definition htlist.H:523
size_t size() const noexcept
Count the number of elements of the list.
Definition htlist.H:1319
__T foldl(const __T &init, Op &op) const
Fold the elements of the container to a specific result.
Definition ah-dry.H:1034
Aleph::DynList< T > filter(Operation &operation) const
Filter the elements of a container according to a matching criteria.
Definition ah-dry.H:1135
void for_each(Operation &operation)
Traverse all the container and performs an operation on each element.
Definition ah-dry.H:685
Aleph::DynList< __T > maps(Operation &op) const
Map the elements of the container.
Definition ah-dry.H:904
void demo_queue()
void demo_dynlist()
void demo_dynarray()
void demo_comparison()
void demo_stack()
Main namespace for Aleph-w library functions.
Definition ah-arena.H:89
DynList< T > maps(const C &c, Op op)
Classic map operation.
T sum(const Container &container, const T &init=T{})
Compute sum of all elements.
STL namespace.
Circular queue implementations backed by arrays.
Stack implementations backed by dynamic or fixed arrays.
Lazy and scalable dynamic array implementation.
Dynamic doubly linked list implementation.
Dynamic queue implementation based on linked lists.
Dynamic stack implementation based on linked lists.
Alias for htlist.H (DynList implementation).