示例#1
0
/* ASSUMES that theDnode can be deleted  *
 * when this Dlist is deleted!!!         *
 *  (if deletesContainedObjects == TRUE) */
status_t
_TDL_Dlist::prependNode ( _TDL_Dnode * theDnode )
{
  if (   (     getFirstNode()     != (_TDL_Dnode *) NULL   )
      && (   ( getLastNode()      == (_TDL_Dnode *) NULL )
	  || ( getLastNode()
	         -> getNextNode() != (_TDL_Dnode *) NULL ) ) )
  {
    TDL::getLogStream()
	  << "[_TDL_Dlist::prependNode]  Warning:  "
	  << "LastNode inconsistent.   Repairing..."
	  << endl;
    repairList();
  }


  if ( getFirstNode() == (_TDL_Dnode *) NULL )
  {
    theDnode -> setNextNode     ( (_TDL_Dnode *) NULL );
    theDnode -> setPreviousNode ( (_TDL_Dnode *) NULL );
    setFirstNode ( theDnode );
    setLastNode  ( theDnode );
  }

  else
  {
    getFirstNode() -> setPreviousNode ( theDnode );
    theDnode -> setNextNode     ( getFirstNode() );
    theDnode -> setPreviousNode ( (_TDL_Dnode *) NULL );
    setFirstNode ( theDnode );
  }

  return SUCCESS;
}
示例#2
0
_TDL_Dnode *
_TDL_Dlist::pop()
{
	/* Error check */
  if (   (     getFirstNode()     != (_TDL_Dnode *) NULL   )
      && (   ( getLastNode()      == (_TDL_Dnode *) NULL )
	  || ( getLastNode()
	         -> getNextNode() != (_TDL_Dnode *) NULL ) ) )
  {
    TDL::getLogStream()
	  << "[_TDL_Dlist::pop]  Warning:  "
	  << "LastNode inconsistent.   Repairing..."
	  << endl;
    repairList();
  }

  if ( getLastNode() == (_TDL_Dnode *)NULL )
  {
    return (_TDL_Dnode *)NULL;
  }
  else
  {
    return removeNode ( getLastNode(), _TDL_Dlist::BACKWARD );
  }
}
示例#3
0
bool pathOption::addNode(int newNode, pathOption &curBest)
{
    /*for (std::multiset<int>::iterator i = minPathSet.begin(); i != minPathSet.end(); i++)
    {
    	std::cout << *i << " ";
    }
    std::cout << std::endl << minPathEstimate << std::endl;*/

    if (curPath.size() < maxDepth)
    {
        openNodes.erase(newNode);
        curDistance += getLastNode().distanceArray[newNode];
        curPath.push_back(newNode);
        //std::cout << "New path: " << getDepth() << std::endl;
        if (curPath.size() >= maxDepth)
        {
            return false;
        }
    }

    if (getEstimate() >= curBest.curDistance)
    {
        //std::cout << "Path removed: " << curDistance << std::endl;
        return false;
    }

    for (std::set<uint8_t>::iterator i = openNodes.begin(); i != openNodes.end(); i++)
    {
        minPathSet.erase(minPathSet.find(getLastNode().distanceArray[*i]));
    }

    updateMinPath();

    return true;
}
示例#4
0
int main(int argc, char *argv[])
{
    struct node node_1 = {'a', NULL};
    struct node node_2 = {'b', NULL};
    struct node node_3 = {'c', NULL};
    struct node node_4 = {'d', NULL};
    struct node node_5 = {'e', NULL};
    struct node* temporaryNode = NULL;
    struct node* iteratorNode = NULL;
    int count = 1;
    struct node*  dynamicNode = NULL;

    printf("Static Linked List funcitons\n");
    insertNode(&node_1, &node_2);
    insertNode(&node_1, &node_3);
    insertNode(&node_1, &node_4);
    insertNode(&node_1, &node_5);

    iteratorNode = &node_1; 
    do {
        temporaryNode = iteratorNode;
        iteratorNode = nextNode(temporaryNode);
        printf("node[%d].value = %c\n", count, temporaryNode->value);
        count++;
    } while(temporaryNode != iteratorNode); 

    printf("Dynamic Linked List functions\n");

    dynamicNode = createNode('1');
    printf("dynamicList at %p\n", dynamicNode);
    printf("dynamicNode.value: %c\n", dynamicNode->value);

    dynamicNode->next = createNode('2');
    temporaryNode = getLastNode(dynamicNode);
    printf("temporaryNode at %p\n", temporaryNode);
    printf("lastNode.value: %c\n", temporaryNode->value);

    temporaryNode->next = createNode('3');
    temporaryNode = getLastNode(dynamicNode);
    printf("temporaryNode at %p\n", temporaryNode);
    printf("lastNode.value: %c\n", temporaryNode->value);

    temporaryNode->next = createNode('4');
    temporaryNode = getLastNode(dynamicNode);
    printf("temporaryNode at %p\n", temporaryNode);
    printf("lastNode.value: %c\n", temporaryNode->value);

    destructLastNode(dynamicNode);
    temporaryNode = getLastNode(dynamicNode);
    printf("temporaryNode at %p\n", temporaryNode);
    printf("lastNode.value: %c\n", temporaryNode->value);

    printf("total of nodes %d\n", allocatedNodes.count);
    destructList(dynamicNode); //frees the linked list
    printf("total of nodes %d\n", allocatedNodes.count);
    forceUnregisterAllNodes();//frees all the nodes allocated
}
示例#5
0
BOOLEAN
_TDL_Dlist::contains (
	      const _TDL_Dnode *     theDnode,
	      _TDL_Dlist::DIRECTION  theSearchDiretion /* = BACKWARD */ ) const
{
  _TDL_Dnode * dnode;

  if ( theSearchDiretion == _TDL_Dlist::FORWARD )
    dnode = getFirstNode();
  else
    dnode = getLastNode();

  while ( dnode != (_TDL_Dnode *) NULL )
  {
    if ( dnode == theDnode )
      return TRUE;

    if ( theSearchDiretion == _TDL_Dlist::FORWARD )
      dnode  = dnode -> getNextNode();
    else
      dnode  = dnode -> getPreviousNode();
  }

  return FALSE;
}
 TreeNode * getLastNode(TreeNode *root){
   if (root == NULL)
     return NULL;
   TreeNode * left = root->left, *right = root->right;
   root->left = NULL;
   root->right = NULL;
   TreeNode * link = root;
   if (left !=NULL){
     root->right = left;
     link = getLastNode(left);
   }
   if (right != NULL){
     link->right = right;
     link = getLastNode(right);
   }
   return link;
 }
示例#7
0
void destructList(struct node* listStart)
{
    struct node* seekNode = NULL;

    do { 
        seekNode = getLastNode(listStart);
        destructLastNode(listStart);
    } while( seekNode != listStart);
}
int main(void)
{

    // input data
    char input_data[] = {'f', 'o', 'o', 'b', 'a', 'r'};
    
    // init
    LinkedList *mylist = newCharList();

    // some input
    int i;
    for (i = 0; i < (int)(sizeof(input_data)/sizeof(input_data[0])); i++)
    {
        printf("insertEnd: %c\n", input_data[i]);
        insertEnd(mylist, newCharNode(input_data[i]));
    }

    // output
    printf("printList: \n");
    printList(mylist);

    // remove some
    printf("remove last node\n");
    removeNode(mylist, getLastNode(mylist));
    printf("remove last node\n");
    removeNode(mylist, getLastNode(mylist));

    // output
    printf("printList: \n");
    printList(mylist);

    // remove list
    printf("remove whole list\n");
    removeList(&mylist);

    // output (error operation)
    printf("try to print an empty list\n");
    printList(mylist);

    return 0;
}
示例#9
0
/** \brief Remove the last item of a list
 *
 * \param[in,out] head Pointer to a list
 * \param[in] freeFunc Function pointer for freeing the memory of the list item
 *
 * Removes the last element of the given list and frees all associated memory.
 * If freeFunc is NULL, it tries to directly free the \a data item of each node.
 * This is useful if \a data is a pointer to a single element (e.g. string, int, ...)
 * For complex elements (e.g. structs) the user needs to provide a node-specific free() function.
 * (For example freeFeedItem() )
 */
void removeLast(NODE *head, listFuncPtr freeFunc) {
	NODE *lastNode = NULL;
	dbg_printf(P_DBG, "Removing last item...");
	lastNode = getLastNode(head);

	if(lastNode) {
		if(freeFunc) {
			freeFunc(lastNode->data);
		} else {
			am_free(lastNode->data);
		}
	}
	deleteLast(&head);
}
示例#10
0
文件: VyLink.c 项目: mueschm/Vyper
//Insert data into the list
void insertLinkData(VyNode* head, void* data, unsigned int dataSize)
{
	//Grab the last node in the list
	head = getLastNode(head);
	VyNode* node;
	//If head has no data then use it to place data into
	if(head->data == NULL)
		node = head;
	else
	{
		//Else create a new node and connect the last node to it
		node = malloc(sizeof(VyNode));
		head->nextNode = node;
	}
	//Insert the data into the node
	node->data = data;
	node->nextNode = NULL;
}
示例#11
0
void EventDeque::removeNode(DQNode *remNode){
	//manage the hash map
	if (getFirstNodeAtTick(remNode->getEventTick()) == remNode){ //if remNode is the one in the hash, remove it
		tickIndex.erase(remNode->getEventTick());
		// if more events exist in that tick
		if (remNode->getNextNode() &&
			remNode->getNextNode()->getEventTick() == remNode->getEventTick()) {
			tickIndex.insert(std::pair<int,DQNode*>(remNode->getEventTick(), remNode->getNextNode()));
		}
	}

	//take care of the deque
	if (size > 1){
		if (remNode->getNextNode() != NULL) {remNode->getNextNode()->setPrevNode(remNode->getPrevNode());}
		if (remNode->getPrevNode() != NULL){remNode->getPrevNode()->setNextNode(remNode->getNextNode());}
	}
	if (remNode == getFirstNode()) {
		firstNode = remNode->getNextNode();
	}
	if (remNode == getLastNode()) {
		lastNode = remNode->getPrevNode();
	}
	size--;
}
示例#12
0
node * insertNode(node *h, float c, int e)
{
    node *n, *p, *q, *last;
    
    if(c == 0)
        return h;//terminate the operation
    
    //create a node (a term)
    n = (node*) malloc(sizeof(node));
    
    //initialize the node (term)
    n->c = c;
    n->e = e;
    n->next = NULL; //temporary initialization

    //connection
    if(h == NULL)
    {//first node
        h = n;
        h->next = h;//make it circular
    }
    else
    {
        int flag = 0;
        p = h;
        do
        {
            if(n->e > p->e)//new node exponent is greater than the current node exponent
            {//new node to be inserted before the current node
                if(p == h)
                {//n will be the new head node
                    last = getLastNode(h);
                    n->next = h;//connect
                    h = n; //set n as head node
                    last->next = h;//make it circular again
                    
                    flag = 1;//connection made
                    break;
                }
                else
                {//n is some intermediate node
                    q->next = n;
                    n->next = p;
                    
                    flag =1 ;
                    break;
                }
            }
            else if(n->e == p->e)//new node exponent is equal to the current node exponent
            {//merge the node
                p->c += n->c;
                free(n);
                if(p->c == 0)
                {//even p has to be deleted
                    if( p == h)
                    {
                        if(h->next == h)
                        {//only one node in the list and that too about to be deleted
                            free(h);
                            h = NULL;
                        }
                        else
                        {
                            last = getLastNode(h);
                            h = h->next; //set next node as new head
                            last->next = h;//set next of last node to refer to new head
                            free(p);
                        }
                    }
                    else
                    {//an intermediate or tail node to be deleted
                        q->next = p->next; //connection reset
                        free(p);
                    }
                }
                
                flag = 1;
                break;
            }
            else
            {//traverse
                q = p;//shadow pointer
                p = p->next;
            }
        }while(p != h);
      
        if(flag == 0)
        {//connection not done yet
         //new node exponent is smallest
         //connect as tail
            q->next = n;//connect as tail
            n->next = h;//make it circular
        }
    }//else
    return h;
}  
示例#13
0
TourNode Ant::selectBestTourNode(NearestSpotList nearest, unsigned int& insertAt, Config::NodeInsertMode insertMode)
{
    // list contains pairs of valid candidates, and their tauEta value
    std::vector<std::pair<TourNode,double>> candidates;   
    double sumP = 0;
    
    std::vector<unsigned> insertPos;
    
    for(const auto& ps : nearest) {
        int tournode = ps.first;
        unsigned spotId = ps.second;
        
        const Spot& nearestspot = problem.getSpot(spotId);
        TourNode lastNode = getLastNode();
	
	unsigned bestInsert = helper.findInsertPosition(instance, tournode, nearestspot, insertMode);
	//double deltaTour = helper.getInsertDeltaTourLength(instance, tournode, nearestspot, insertMode, bestInsert);
	
        // check all methods of this spot
        unsigned methodId = 0;
        for (const auto& m : nearestspot.getMethods()) {
            
	    TourNode newNode(spotId, methodId);
	    TourValues insertValues = getInsertValues(tournode, newNode, insertAt);
	    
	    double tauEta = getTauEta(lastNode, newNode, insertValues);
            
	    if (!instance.isValid(insertValues)) {
		// TODO What happens if the new node causes the tour to get invalid? Several approches:
		// - continue; (but this does not allow us to create tours that are larger than the maximum!)
		//   don't forget to do methodId++;
		// - or set tauEta to something low so that it gets unlikely (but not impossible) that it will be picked
		tauEta *= 0.01;
	    }
            
	    sumP += tauEta;
	    candidates.push_back(std::make_pair(newNode,tauEta));
	    insertPos.push_back(bestInsert);

            methodId++;
        }
    }
    
    double r = ((double) rand() / (RAND_MAX));
    double p = 0.0;
    
    int i = 0;
    for (auto& entry : candidates) {
        if (p + entry.second/sumP > r) {
	    insertAt = insertPos[i];
            return entry.first;
	} else {
            p += entry.second/sumP;
	}
	i++;
    }

    // we should only reach that point if our tauEtaList is empty (i.e. we found no usable methods), 
    // we return just some best guess here
    return TourNode(nearest.front().second, 0);
}
示例#14
0
	/* Note:  Does NOT delete theDnode. *
	 * Returns NULL for failure.        */
_TDL_Dnode *
_TDL_Dlist::removeNode( _TDL_Dnode *           theDnode,
			_TDL_Dlist::DIRECTION  theSearchDiretion /*=BACKWARD*/)
{
  _TDL_Dnode * dnode;
  _TDL_Dnode * lastDnode = (_TDL_Dnode *) NULL;

	/* Error check */
  if (   (     getFirstNode()     != (_TDL_Dnode *) NULL   )
      && (   ( getLastNode()      == (_TDL_Dnode *) NULL )
	  || ( getLastNode()
	         -> getNextNode() != (_TDL_Dnode *) NULL ) ) )
  {
    TDL::getLogStream()
	  << "[_TDL_Dlist::removeNode]  Warning:  "
	  << "LastNode inconsistent.   Repairing..."
	  << endl;
    repairList();
  }


  if ( theSearchDiretion == _TDL_Dlist::FORWARD )
    dnode = getFirstNode();
  else
    dnode = getLastNode();

  while ( dnode != (_TDL_Dnode *) NULL )
  {
    if ( dnode == theDnode )
    {
      if ( lastDnode == (_TDL_Dnode *) NULL )
      {
	if ( theSearchDiretion == _TDL_Dlist::FORWARD )
	{
	  setFirstNode ( dnode -> getNextNode() );
	  if ( dnode -> getNextNode() != (_TDL_Dnode *) NULL )
	    dnode -> getNextNode() -> setPreviousNode ( (_TDL_Dnode *) NULL );
	}
	else
	{
	  setLastNode ( dnode -> getPreviousNode() );
	  if ( dnode -> getPreviousNode() != (_TDL_Dnode *) NULL )
	    dnode -> getPreviousNode() -> setNextNode ( (_TDL_Dnode *) NULL );
	}
      }
      else
      {
	if ( theSearchDiretion == _TDL_Dlist::FORWARD )
	{
	  lastDnode -> setNextNode ( dnode -> getNextNode() );
	  if ( dnode -> getNextNode() != (_TDL_Dnode *) NULL )
	    dnode -> getNextNode() -> setPreviousNode ( lastDnode );
	}
	else
	{
	  lastDnode -> setPreviousNode ( dnode -> getPreviousNode() );
	  if ( dnode -> getPreviousNode() != (_TDL_Dnode *) NULL )
	    dnode -> getPreviousNode() -> setNextNode ( lastDnode );
	}
      }

      if (   ( theSearchDiretion == _TDL_Dlist::FORWARD )
	  && (   ( getLastNode()          == dnode               )
	      || ( dnode -> getNextNode() == (_TDL_Dnode *) NULL ) ) )
      {
	setLastNode ( lastDnode );
	if ( lastDnode != (_TDL_Dnode *) NULL )
	  lastDnode -> setNextNode ( (_TDL_Dnode *) NULL );
      }

      if (   ( theSearchDiretion != _TDL_Dlist::FORWARD )
	  && (   ( getFirstNode()             == dnode               )
	      || ( dnode -> getPreviousNode() == (_TDL_Dnode *) NULL ) ) )
      {
	setFirstNode ( lastDnode );
	if ( lastDnode != (_TDL_Dnode *) NULL )
	  lastDnode -> setPreviousNode ( (_TDL_Dnode *) NULL );
      }

      dnode -> setNextNode     ( (_TDL_Dnode *) NULL );
      dnode -> setPreviousNode ( (_TDL_Dnode *) NULL );
      return dnode;
    }

    else
    {
      lastDnode = dnode;

      if ( theSearchDiretion == _TDL_Dlist::FORWARD )
	dnode  = dnode -> getNextNode();
      else
	dnode  = dnode -> getPreviousNode();
    }
  } /* WHILE ( dnodes ) */


  return (_TDL_Dnode *) NULL;
}
 void flatten(TreeNode *root) {
   // Start typing your C/C++ solution below
   // DO NOT write int main() function
   getLastNode(root);
 }
int main(int argc, char* argv[])
{
	/* Declarations */
	List list;
	List list_1;
	List list_2;
	List list_3;
	List list_4;
	List list_5;
	List list_6;
	Position pos;
	Position pos_1;
	Position pos_2;
	Position pos_3;
	Position pos_4;
	Position pos_a, pos_b;
	int len;
	int idx;
	ElementType elem;

	/* Initialize list */
	list=createList();

	/* Test functions 'insertNode' and 'appendNode' */
	printf("Test functions 'insertNode' and 'appendNode'\n\n");
	printf("Before 'insertNode':\n");
	printList(list);
	pos_1=getHeaderNode(list);
	insertNode(11, list, pos_1);
	pos_2=advanceNode(pos_1);
	insertNode(2, list, pos_2);
	pos_3=advanceNode(pos_2);
	insertNode(3, list, pos_3);
	pos_4=advanceNode(pos_3);
	insertNode(10, list, pos_4);
	insertNode(9, list, pos_2);
	printf("After 'insertNode':\n");
	printList(list);
	printf("Before 'appendNode':\n");
	printList(list);
	appendNode(7, list);
	appendNode(2, list);
	printf("After 'appendNode'\n");
	printList(list);
	printf("\n");

	/* Test functions 'cloneList', 'deleteNode' and 'deleteList' */
	printf("Test functions 'cloneList', 'deleteNode' and 'deleteList'\n\n");
	list_1=cloneList(list);
	printf("Before 'deleteNode':\n");
	printList(list_1);
	deleteNode(2, list_1);
	printf("After 'deleteNode':\n");
	printList(list_1);
	printf("Before 'deleteList':\n");
	printList(list_1);
	deleteList(list_1);
	printf("After 'deleteList':\n");
	printList(list_1);
	printf("\n");

	/* Test function 'getListLength' */
	printf("Test function 'getListLength'\n\n");
	len=getListLength(list);
	printf("Length: %d\n", len);
	printf("\n");

	/* Test functions 'findNode', 'findNodePrevious' and 'getNodeIndex' */
	printf("Test functions 'findNode', 'findNodePrevious' and 'getNodeIndex'\n\n");
	elem=2;
	pos=findNode(elem, list);
	if(pos!=NULL)
	{
		idx=getNodeIndex(pos, list);
		printList(list);
		printf("finding %d, Element at index %d found\n", elem, idx);
	}
	else
	{
		printf("finding %d, not found\n", elem);
	}
	elem=3;
	pos=findNodePrevious(elem, list);
	/* Check whether elem is found in list */
	if(pos->m_next!=NULL)
	{
		idx=getNodeIndex(pos, list);
		printf("finding previous element of %d, Element at index %d found\n", elem, idx);
	}
	else
	{
		/* elem is not in list */
		printf("finding previous element of %d, not found\n", elem);
	}
	printf("\n");

	/* Test functions 'makeListEmpty' and 'isListEmpty' */
	printf("Test functions 'makeListEmpty' and 'isListEmpty'\n\n");
	list_2=cloneList(list);
	printf("Before 'makeListEmpty':\n");
	printList(list_2);
	list_2=makeListEmpty(list_2);
	if(isListEmpty(list_2))
	{
		printf("List emptied successfully\n");
		printf("After 'makeListEmpty'\n");
		printList(list_2);
	}
	printf("\n");

	/* Test functions 'getHeaderNode', 'getFirstNode', 'getLastNode', 'advanceNode' and 'getNodeElem' */
	printf("Test functions 'getHeaderNode', 'getFirstNode', 'getLastNode', 'advanceNode' and 'getNodeElem'\n\n");
	printList(list);
	pos=getHeaderNode(list);
	printf("Header at index %d\n", getNodeIndex(pos, list));
	pos=getFirstNode(list);
	printf("First element at index %d have value %d\n", getNodeIndex(pos, list), getNodeElem(pos));
	pos=getLastNode(list);
	printf("Last element at index %d have value %d\n", getNodeIndex(pos, list), getNodeElem(pos));
	pos=getFirstNode(list);
	pos=advanceNode(pos);
	printf("Second element at index %d have value %d\n", getNodeIndex(pos, list), getNodeElem(pos));
	printf("\n");

	/* Test function 'reverseList' */
	printf("Test function 'reverseList'\n\n");
	list_3=cloneList(list);
	printf("Before 'reverseList':\n");
	printList(list_3);
	list_3=reverseList(list_3);
	printf("After 'reverseList':\n");
	printList(list_3);
	printf("\n");

	/* Test function 'swapNode' */
	printf("Test function 'swapNode'\n\n");
	list_4=cloneList(list);
	printf("Before 'swapNode':\n");
	printList(list_4);
	pos_a=getHeaderNode(list_4);
	pos_a=advanceNode(pos_a);
	pos_a=advanceNode(pos_a);
	pos_b=advanceNode(pos_a);
	swapNode(pos_a, pos_b, list_4);
	printf("After 'swapNode':\n");
	printList(list_4);
	printf("\n");

	/* Test function 'bubbleSortList' */
	printf("Test function 'bubbleSortList'\n\n");
	list_5=cloneList(list);
	printf("Before 'bubbleSortList':\n");
	printList(list_5);
	bubbleSortList(list_5);
	printf("After 'bubbleSortList':\n");
	printList(list_5);
	printf("\n");

	/* Test function 'connectList' */
	printf("Test function 'connectList'\n\n");
	printf("List 1:\n");
	printList(list);
	printf("Length: %d\n", getListLength(list));
	printf("List 2:\n");
	printList(list_5);
	printf("Length: %d\n", getListLength(list_5));
	list_6=connectList(list, list_5);
	printf("Connected list:\n");
	printList(list_6);
	printf("Length: %d\n", getListLength(list_6));
	printf("\n");

	/* Cleanup memory */
	destroyList(list);
	destroyList(list_1);
	destroyList(list_2);
	destroyList(list_3);
	destroyList(list_4);
	destroyList(list_5);
	destroyList(list_6);

	return 0;
}
示例#17
0
void pathOption::addNodeForce(int newNode)
{
    openNodes.erase(newNode);
    curDistance += getLastNode().distanceArray[newNode];
    curPath.push_back(newNode);
}