Commits

Enrico Franchi committed 071cd36

Added merge method.

Comments (0)

Files changed (1)

 
 
 void
-Fibonacci_Tree_Exit(Fibonacci_Tree* tree) {
+Fibonacci_Tree_Free_Memory(Fibonacci_Tree* tree) {
     if (tree->Deg_Tab != NULL) {
       PyMem_Free(tree->Deg_Tab);
     }
 }
 
 void
-Fibonacci_Tree_Self_Link(Fibonacci_Tree* tree)
+Fibonacci_Tree_Forget_Roots(Fibonacci_Tree* tree)
 {
   tree->root.prev =              /* Link root node to itself */
   tree->root.next = &tree->root;
+  tree->len = 0;
 }
 
 
 Fibonacci_Tree_Dealloc(Fibonacci_Tree* tree) {
     PyObject_GC_UnTrack(tree);
     Fibonacci_Tree_Clear(tree);
+    Fibonacci_Tree_Free_Memory(tree);
+    Fibonacci_Tree_Forget_Roots(tree);
     Py_TYPE(tree)->tp_free(tree);
 }
 
 }
 PyDoc_STRVAR(copy_doc, "Makes a copy of the tree.");
 
+static void
+Fibonacci_Tree_Destructive_Merge(Fibonacci_Tree* first,
+                                 Fibonacci_Tree* second) {
+    /* very dangerous to call from Python as it does not have the usual
+     * python semantics.
+     */
+    first->len += second->len;
+
+    first->root.prev->next = second->root.next;
+    second->root.prev->next = &first->root;
+    second->root.next->prev = first->root.prev;
+    first->root.prev = second->root.prev;
+
+    Fibonacci_Tree_Forget_Roots(second);
+}
+
+static PyObject*
+Fibonacci_Tree_Merge(Fibonacci_Tree* tree, PyObject* other) {
+    Fibonacci_Tree* copy =
+        (Fibonacci_Tree*)Fibonacci_Tree_Copy((Fibonacci_Tree*)other);
+    if(copy != NULL) {
+        Fibonacci_Tree_Destructive_Merge(tree, copy);
+        Py_DECREF(copy);
+        Py_RETURN_NONE;
+    } else {
+        return 0;
+    }
+}
+PyDoc_STRVAR(merge_doc, "Merges the values of second tree into the first tree.");
 
 /*
 static int
     {"peek", (PyCFunction)Fibonacci_Tree_Peek, METH_NOARGS, peek_doc},
     {"push", (PyCFunction)Fibonacci_Tree_Add, METH_O, push_doc},
     {"extend", (PyCFunction)Fibonacci_Tree_Extend, METH_O, extend_doc},
+    {"merge", (PyCFunction)Fibonacci_Tree_Merge, METH_O, merge_doc},
+
     {NULL, NULL, 0, NULL},
 };