d58f20fb7b8b0e2b236988230fd696b757ae2116
[feisty_meow.git] / nucleus / library / nodes / singly_linked_list.h
1 #ifndef SINGLY_LINKED_LIST_CLASS
2 #define SINGLY_LINKED_LIST_CLASS
3
4 /*
5 *  Name   : singly_linked_list
6 *  Author : Chris Koeritz
7 **
8 * Copyright (c) 1998-$now By Author.  This program is free software; you can
9 * redistribute it and/or modify it under the terms of the GNU General Public
10 * License as published by the Free Software Foundation; either version 2 of
11 * the License or (at your option) any later version.  This is online at:
12 *     http://www.fsf.org/copyleft/gpl.html
13 * Please send any updates to: fred@gruntose.com
14 */
15 #include "node.h"
16
17 namespace nodes {
18
19 //class node;  // forward.
20
21 //! Implements a singly-linked list structure.
22
23 class singly_linked_list : public node
24 {
25 public:
26   singly_linked_list() : node(1) {}
27
28   //hmmm: clean up all children?
29   ~singly_linked_list() {}
30
31   const int NEXT_NODE = 0;  // symbol for the rest of the list linked here.
32
33   int elements() const;
34     //!< returns the number of items currently in the list, including this node.
35     /*!< this is a costly operation. */
36
37   singly_linked_list *next() { return (singly_linked_list *)get_link(NEXT_NODE); }
38
39   void set_next(singly_linked_list *new_next) { set_link(NEXT_NODE, new_next); }
40
41   //! returns true if this list has a cycle in it.
42   static bool has_cycle(singly_linked_list *check) {
43         singly_linked_list *a = check;
44         singly_linked_list *b = check;
45         while ((a != NULL_POINTER) && (b!= NULL_POINTER) ) {
46                 a = a->next();  // move position of a forward once.
47           // move position of b forward twice.
48                 b = b->next();
49                 if (b != NULL_POINTER) b = b->next();
50
51                 if (a == b) {
52                         // argh, our single skipper and double skipper have arrived at the same node.
53                         // the only way that can happen is if there's a cycle in the list.
54                         return true;
55                 }
56         }
57         // if we fell out of the list iteration with a null for either pointer,
58         // then there was no cycle in the list.
59         return false;
60   }
61
62 private:
63   // not permitted.
64   singly_linked_list(const singly_linked_list &);
65   singly_linked_list &operator =(const singly_linked_list &);
66 };
67
68 } // namespace.
69
70 #endif
71