Beispiel #1
0
int main() {
	int data1,data2,data3,data4,data5;
	int nonData = 6;
	int * pFind = NULL;
	List test = NULL;
	initList(&test);

	data1 = 10;data2 = 20;data3 = 30;data4 = 40;data5 = 50;
	addToList(test, (void*)&data1);
	addToList(test, (void*)&data2);
	addToList(test, (void*)&data3);
	addToList(test, (void*)&data4);
	addToList(test, (void*)&data5);
	displayList(test);

	printf("%s","Searching for 30");
	pFind = (int*)findInList(test, (void*)&data3, intGreater);

	if (pFind)
	{
		printf("%s%d","\nFound data value: ", *pFind);
	}
	else {
		printf("%s","\nData not found");
	}

	printf("%s","\nSearching for 99 (shouldn't be in list)");
	pFind = (int*)findInList(test, (void*)&nonData, intGreater);

	if (pFind)
	{
		printf("%s%d","\nFound data value: ", *pFind);
	}
	else {
		printf("%s","\nData not found");
	}

	printf("%s","\nremoving one item then displaying\n");
	removeFirst(test);
	displayList(test);

	printf("%s","removing all items then displaying\n");
	deleteList(test);
	displayList(test);

	printf("%s","Attempting to remove from an empty list\n");
	removeFirst(test);
	displayList(test);

	cleanupList(&test);

	printf("%s","All tests complete\n");

	return 0;
}
Beispiel #2
0
void List::removeByIndex(uint index)
{
    if (index == 0)
    {
        removeFirst();
    }
    else if (index == _count - 1)
    {
        pop();
    }
    else 
    {
        Node* element = elementByIndex(index);
        if (element != NULL)
        {
            _count--;

            //// у i-го берем і-1 ставим следующий і+1
            //Node* temp = element->getPrev();
            //temp->setNext(element->getNext());

            //// у i-го берем і+1 ставим предыдущий і-1
            //temp = element->getNext();
            //temp->setPrev(element->getPrev());
            //
            //// бахаем і-й
            //delete element;

            // in short form
            element->getPrevious()->setNext(element->getNext());
            element->getNext()->setPrevious(element->getPrevious());
            delete element;
        }
    }
}
Beispiel #3
0
TYPE Sequence<TYPE>::remove(int pos)
{
    Node *aux = &list;
    Node *aux7 = &list;
    while (aux->next != NULL)
    {
        if(pos <= 0)
            return removeFirst();
        else
        {
            if(pos == 0)
            {
                if(aux->next != NULL)
                {
                    Node *toBeDeleted = aux->next;
                    aux->next = aux->next->next;
                    delete toBeDeleted;
                    return true;
                }
                else
                    break;
            }
        }
        pos--;
        aux = aux->next;
    }
    if(aux7->next != NULL)
        removeLast();
    return false;
}
/* Adds a command to the history list, deleting the first if the 
* size of the list is too large */
void addCommandToHistory(char* command_line)
{
    history_item* theItem = (history_item*)malloc(sizeof(history_item));
    
    if(history_list == NULL)
    {
        initHistory();
    }
    if(length(history_list) == 0)
    {
        theItem->command_number = 1;
    }
    else
    {
        theItem->command_number = 
            1 + ((history_item*)(history_list->tail->data))->command_number;
    }
    
    theItem->command_line = command_line;

    addLast(history_list, theItem);
    if(length(history_list) > HISTORY_LENGTH)
    {
        free(((history_item*)(history_list->head->data))->command_line);
        free(history_list->head->data);
        removeFirst(history_list);
    }
}
Beispiel #5
0
Sequence<TYPE>::~Sequence()
{
    while(!isEmpty())
    {
        removeFirst();
    };
}
Beispiel #6
0
Grantlee::Node *FilterNodeFactory::getNode(const QString &tagContent,
                                           Grantlee::Parser *p) const
{
  auto expr = tagContent.split(QLatin1Char(' '), QString::SkipEmptyParts);

  expr.removeFirst();

  auto expression = expr.join(QChar::fromLatin1(' '));
  FilterExpression fe(QStringLiteral("var|%1").arg(expression), p);

  auto filters = fe.filters();
  if (filters.contains(QStringLiteral("safe"))
      || filters.contains(QStringLiteral("escape"))) {
    throw Grantlee::Exception(
        TagSyntaxError, QStringLiteral("Use the \"autoescape\" tag instead."));
  }

  auto n = new FilterNode(fe, p);

  auto filterNodes = p->parse(n, QStringLiteral("endfilter"));
  p->removeNextToken();

  n->setNodeList(filterNodes);
  return n;
}
Beispiel #7
0
// removes last element of list
void*CList::removeLast(bool freeData)
{
  if(first == last) {
    return removeFirst(freeData);
  }

  CListItem *tmp = last;
  CListItem *iter = first;

  while(iter->next != last)
  {
    iter = iter->next;
  }

  // iter->next == last
  iter->next = NULL;
  last = iter;

  void*result;
#ifdef DOFREE
  if(freeData) {
    free(tmp->data);
    tmp->data = NULL;
  }
#endif
  result = tmp->data;

  free(tmp);
  length--;
  if(length <= 0) {
    length = 0;
  }

  return result;
}
Beispiel #8
0
//---------------------------------------
void FRDialog::updateItemforTable(QStringList &booklist, QStringList &chapterlist)
{
    QStringList booklib, chapterlib;

    for (int i = 0; i < booklist.size(); i++)
    {
        QString name = getFileNameAbs(QString(booklist.at(i)));
        QString namebook = QString(name)
                .remove("book_")
                .remove("chapter_");
        QString namechapter = namebook;
        QStringList list;
        list = namebook.split("_");
        namebook = list.first();

        namechapter = QString(namechapter)
                .remove("_");
        namechapter = removeFirst(namechapter, namebook);

        QString filenamebook = Config::configuration()->CurPrjDir()
                + "/" + "book_" + namebook + ".htm";

        namechapter = tr("Chapter ") + namechapter;

        namebook = getParamBook(filenamebook, "FullName");
        booklib << namebook;
        chapterlib << namechapter;
    }
    booklist = booklib;
    chapterlist = chapterlib;
//    qDebug() << "\nlist1 = " << booklist
//             << "\n\n list2 = " << chapterlist;
}
Beispiel #9
0
void Liste::remove(int index){
	if(index < 0){
		index = _len + index;
	}
	
	if(index < 0 || index >= _len){
		//TODO TROW ERR
		cout << "ERROR remove index out of range" << endl;
		return;
	}
	
	if(index == 0){
		removeFirst();
	} else if(index == _len-1) {
		removeLast();
	} else {
		ListeItem *r = _getItem(index);
		ListeItem *b = r->_back;
		ListeItem *f = r->_front;
		
		b->_front = f;
		f->_back = b;
		
		delete r;
		_len--;	
	}
}
Beispiel #10
0
    /**
     * Remove any element e for which predicate(e) returns true.
     */
    int removeAll(std::function<bool (const T&)> predicate)
    {
        const std::vector<T> &matches = items(predicate);
        for(const auto &elt : matches) {
            removeFirst(elt);
        }

        return matches.size();
    }
Beispiel #11
0
bool DLList::removeAll (int target) {
    bool valueDeleted = false;
    for (unsigned int i = 0; i < count; i++) {
        if (removeFirst(target) == true) {
            valueDeleted = true;
        }
    }
    return valueDeleted;
}
Beispiel #12
0
	void TagManager::removeEntity(const EntityInfo& e)
	{
		std::string tag = _tagsByEntity[e.getId()];
		std::vector<Entity>& entities = _entityArraysByTag[tag];

		removeFirst(entities, (Entity)e);

		_tagsByEntity[e.getId()] = "";
	}
Beispiel #13
0
struct number * parseNum(char* number){
	struct number *num;
	num = (struct number *)malloc(sizeof(struct number));
	long dec;
	if(number[0]== '-'){
		num->negative = true;
		char type = number[1];
		number = removeFirst(number);
		number = removeFirst(number);
		if(type == 'b'){
			num->binary = number;
			dec = conBinToDec(number);
		}else if(type == 'o'){
			num->oct = number;
			dec = conOctToDec(number);
		}else if(type == 'x'){
			num->hex = number;
			dec = conHexToDec(number);
		}else{
			dec = atol(number);
		}
		printf("%s\n", number);
		num->decimal = dec;
	}else{
		num->negative = false;
		char type = number[0];
		number = removeFirst(number);
		if(type == 'b'){
			num->binary = number;
			dec = conBinToDec(number);
		}else if(type == 'o'){
			num->oct = number;
			dec = conOctToDec(number);
		}else if(type == 'x'){
			num->hex = number;
			dec = conHexToDec(number);
		}else{
			dec = atol(number);
		}
		printf("%s\n", number);
		num->decimal = dec;
	}
	return num;
}
Beispiel #14
0
  T deque<T>::removeLast()
  {
    if (head.get() == tail)
      return removeFirst();

    T elt = tail->first;
    tail = tail->prev;
    tail->rest = nullptr;

    return elt;
  }
bool DLList::removeAll(int target) {
  bool targetFound = false;

  if (head == NULL)
    return targetFound;
  for (unsigned int i = 0; i < size; i++) {
      removeFirst(target); 
      targetFound = true;
  }
  return targetFound;
}
Beispiel #16
0
void freeList(LinkedList *lL)
{
	LinkedListNode *tempPtr;
	tempPtr = lL->head;
	//free each element
	while (tempPtr != NULL)
	{
		removeFirst(lL);
		tempPtr= lL->head;
	}
	free(lL); //free list
}
Beispiel #17
0
  T deque<T>::remove(loc lnk)
  {
    if (tail == lnk) 
      return removeLast();
    else if (head.get() == lnk)
      return removeFirst();
    
    // no special cases, so we can just update the links
    lnk->rest->prev = lnk->prev;
    lnk->prev->rest = move(lnk->rest);

    return lnk->first;
  }
Beispiel #18
0
int main(int argc, char* argv[]){  
    Point p1;
    p1.x = 1; p1.y = 2;  
    Point p2;
    p2.x = 3; p2.y = 4; 
    
    List list = initList(sizeof(Point));
    insertFirst(list, &p1);
    insertFirst(list, &p2);  
    
    Point* test[2];
    test[0] = (Point*) removeFirst(list);
    test[1] = (Point*) removeFirst(list);
     
    /*
    printf("p2.x: %d, p2.y: %d\n", test[0]->x, test[0]->y);
    printf("p1.x: %d, p1.y: %d\n", test[1]->x, test[1]->y);
    */
    liberer(list);
    
    return !(test[0]->x==3 && test[0]->y==4 && test[1]->x==1 && test[1]->y==2);
}
Beispiel #19
0
static void buildMaze(int y, int x)
{
    int numOffsets, offset, offsets[4];


    while (1) {
	numOffsets = 0;
	maze[y][x].visited = true;

	if (y > 0 && !maze[y - 1][x].visited)
	    offsets[numOffsets ++] = -width;

	if (y < height - 1 && !maze[y + 1][x].visited)
	    offsets[numOffsets ++] = width;

	if (x > 0 && !maze[y][x - 1].visited)
	    offsets[numOffsets ++] = -1;

	if (x < width - 1 && !maze[y][x + 1].visited)
	    offsets[numOffsets ++] = 1;

	if (numOffsets > 0) {
	    offset = offsets[rand() % numOffsets];
	    addFirst(dp, offset(x, y));

	    if (offset == -width) {
		maze[y - 1][x].bottom = false;
		buildMaze(y - 1, x);
	    } else if (offset == width) {
		maze[y][x].bottom = false;
		buildMaze(y + 1, x);
	    } else if (offset == -1) {
		maze[y][x - 1].right = false;
		buildMaze(y, x - 1);
	    } else if (offset == 1) {
		maze[y][x].right = false;
		buildMaze(y, x + 1);
	    } else
		abort();

	} else if (numItems(dp) > 0) {
	    offset = removeFirst(dp);
	    x = xcoord(offset);
	    y = ycoord(offset);

	} else
	    break;
    }

    maze[height - 1][width - 1].right = false;
}
    /// \details
    /// This routine is called from the timer interrupt service routine
    /// to count ticks and to wake-up the sleeping threads when their
    /// associated counters reach zero.
    ///
    /// Due to the way ticks are stored relatively to the previous element,
    /// only the top counter needs to be decremented. When zero is
    /// reached, the thread related to the current element and the threads
    /// related to all following elements with ticks=0 will be waked-up.
    void
    TimerBase::interruptServiceRoutine(void)
    {
#if defined(DEBUG) && defined(OS_DEBUG_TIMERBASE_INTERRUPTTICK)
      os::diag::trace.putChar('[');
#endif // defined(DEBUG) && defined(OS_DEBUG_TIMERBASE_INTERRUPTTICK)
      // Increment the perpetual ticks counter. Will obviously overflow
      // and start from 0.
      m_ticks++;

      // Decrement timer and eventually wake-up thread
      if (m_count > 0) // is there anything in the list?
        {
#if defined(DEBUG) && defined(OS_DEBUG_TIMERBASE_INTERRUPTTICK)
          os::diag::trace.putChar('*');
#endif // defined(DEBUG) && defined(OS_DEBUG_TIMERBASE_INTERRUPTTICK)
          volatile timer::Element* p;
          p = m_pArray;

          // Decrement the counter associated with the first element
          if (--(p->ticks) == 0)
            {
              do
                {
#if defined(DEBUG) && defined(OS_DEBUG_TIMERBASE_INTERRUPTTICK)
                  os::diag::trace.putString(" tw(");
                  os::diag::trace.putString(p->pThread->getName());
                  os::diag::trace.putString(",");
                  os::diag::trace.putDec(m_count);
                  os::diag::trace.putString(") ");
#endif // defined(DEBUG) && defined(OS_DEBUG_TIMERBASE_INTERRUPTTICK)
                  // Sleep period completed, wake-up the thread
                  p->pThread->wakeupNoInterrupts();

                  // Remove the top element from the array

                  // MANDATORY, otherwise this routine hangs with
                  // an infinite loop!
                  removeFirst();
                }
              while ((p->ticks == 0) && (m_count > 0));
            }
        }

#if defined(DEBUG) && defined(OS_DEBUG_TIMERBASE_INTERRUPTTICK)
      os::diag::trace.putChar(']');
#endif // defined(DEBUG) && defined(OS_DEBUG_TIMERBASE_INTERRUPTTICK)
    }
Beispiel #21
0
void trimList()
{

	if(HISTCOUNT > HISTFILECOUNT)
	{
		HISTMAX = HISTCOUNT;
	}
	else
	{
		HISTMAX = HISTFILECOUNT;
	}
	while((*HISTORY).size >= HISTMAX)
	{
		removeFirst(HISTORY, cleanHistory);
	}
}
Beispiel #22
0
void PacketBuffer::put(const Packet &packet)
{
	lock();
	while (pos > backwardPackets)
	{
		const Packet &tmpPacket = first();
		backward_duration -= tmpPacket.duration;
		backward_bytes -= tmpPacket.size();
		removeFirst();
		--pos;
	}
	append(packet);
	remaining_bytes += packet.size();
	remaining_duration += packet.duration;
	unlock();
}
Beispiel #23
0
// assignment operator
DoublyLinkedList& DoublyLinkedList::operator=(const DoublyLinkedList& dll) //O(n)
{
	
	while (!isEmpty()){
		removeFirst();
	} 
  
    header.next = &trailer; trailer.prev = &header;
    DListNode *current = dll.getFirst();
    while(current != dll.getAfterLast())
	{
  	  insertFirst(current->getElem());
	  current=current->getNext();
    }
	
	return *this;
}
Beispiel #24
0
/*This Func Del an Existing User By Key*/
Item delRecByKey(List *ptrList,Item *ptritem)
{
	Node *tmpitem,*deleteNode;
	Item tmp={"No Item"};

	if(!ptrList)
	{
		NO_LIST;
		return tmp;
	}

	if(ListIsEmpty(ptrList))
	{
		Item tmp={"No Item"};
		LIST_IS_EMPTY;
		return tmp;
	}

	tmpitem=ptrList->start;

	if(COMPARE(*ptritem,tmpitem->data))
	{/*in case that the 1st is to delete*/
		tmp=removeFirst(ptrList);
		return tmp;
	}

	while(tmpitem->next)
	{
		if(COMPARE(tmpitem->next->data,*ptritem))
		{
			if (tmpitem->next == ptrList->end)
				ptrList->end = tmpitem;
			tmp=tmpitem->next->data;
			deleteNode=tmpitem->next;
			tmpitem->next=tmpitem->next->next;
			free(deleteNode);
			ptrList->num--;
			return tmp;
		}
		tmpitem=tmpitem->next;
	}
	
	return tmp;
}
Beispiel #25
0
	void TagManager::setTag(const EntityInfo& e, std::string tag)
	{
		_tagsByEntity.resize(e.getId()+1);

		// Get old tag
		std::string oldTag = _tagsByEntity[e.getId()];

		std::vector<Entity>& oldTagEntities = _entityArraysByTag[oldTag];
		std::vector<Entity>& newTagEntities = _entityArraysByTag[tag];

		// Set entity's tag
		_tagsByEntity[e.getId()] = tag;

		// Remove entity from old tag collection
		removeFirst(oldTagEntities, (Entity)e);

		// Add entity to new tag collection
		newTagEntities.push_back(e);
	}
Beispiel #26
0
int main( int argc, char *argv[] ){
	QCoreApplication a( argc, argv );
	Overmix::ImageContainer images;
	Overmix::CommandParser parser( images );
	
	try{
		//Parse command-line arguments
		auto args = a.arguments();
		args.removeFirst();
		parser.parse( args );
		
		return 0;
	}
	catch( std::exception& e ){
		std::cout << "Some error occurred:" << std::endl;
		std::cout << e.what();
		return -1;
	}
}
Beispiel #27
0
void ReachableList::calculateNewList()
{
  // qDebug( "ReachableList::calculateNewList() is called" );

  // calculateNewList is also called from calculator, so on check has to be
  // executed
  if ( !isOn() )
    {
      return;
    }

  // QTime t; // timer for performance measurement
  // t.start();

  setInitValues();
  clearLists();  // clear all lists

  // Now add items of different type to the list
  addItemsToList(MapContents::AirfieldList);
  addItemsToList(MapContents::GliderfieldList);
  addItemsToList(MapContents::OutLandingList);
  addItemsToList(MapContents::WaypointList);
  modeAltitude = false;
  //qDebug("Number of potential reachable sites: %d", count() );

  // sort list according to distances
  qSort(begin(), end() );
  removeDoubles();
  // qDebug("Number of potential reachable sites (after pruning): %d", count() );

  // Remove all elements over the maximum. That are the far away elements.
  int nr = getMaxNrOfSites();

  while ( nr < size() )
    {
      removeFirst();
    }

  // qDebug("Limited Number of potential reachable sites: %d", count() );
  calculateDataInList();
  //qDebug("Time for full calculation: %d msec", t.restart() );
}
/**
   Parses a string in the format `a = 1,b=2, c = "1,2,3,4", d = 5.0, e='a,b,c'`
   into a map of key/value pairs
   @param qstr The input string
   @throws std::runtime_error on an invalid input string
   @returns : a map of key/value pairs as QStrings
*/
std::map<QString, QString> parseKeyValueQString(const QString &qstr) {
  /*
    This is a bad example of using a tokenizer, and
    Mantid::Kernel::StringTokenizer should
    ideally be used for this (see LoadProcessedNexus, Fit1D or others for
    examples)

    The reason we must use boost::tokenizer here is that passing a list of
    separators is not
    yet possible with Mantid::Kernel::StringTokenizer.
  */
  auto str = qstr.toStdString();
  boost::tokenizer<boost::escaped_list_separator<char>> tok(
      str, boost::escaped_list_separator<char>("\\", ",", "\"'"));
  std::map<QString, QString> kvp;

  for (const auto &it : tok) {
    auto keyValueString = QString::fromStdString(it);
    auto valVec = keyValueString.split("=");

    if (valVec.size() > 1) {
      // We split on all '='s. The first delimits the key, the rest are assumed
      // to be part of the value
      auto key = valVec[0].trimmed();
      // Drop the key from the values vector
      valVec.removeFirst();
      // Join the remaining sections
      auto value = valVec.join("=").trimmed();

      if (key.isEmpty() || value.isEmpty())
        throw std::runtime_error("Invalid key value pair, '" + it + "'");

      kvp[key] = value;
    } else {
      throw std::runtime_error("Invalid key value pair, '" + it + "'");
    }
  }
  return kvp;
}
Beispiel #29
0
/*Tar bort noden innehållande value (går självklart även att
göra på position)
Pre - listan är inte tom och det finns en nod innehållande
value i listan
Post - noden innehållande value är borttagen*/
void removeNode(List *myList, int pos)
{
	if (pos == 1)
	{
		removeFirst(myList);
		
	}
	else if (pos == myList->numberOfNodes)
	{
		removeLast(myList);
	}
	else if (pos > 1 && pos < myList->numberOfNodes)
	{
		Node* remove = myList->head;
		Node* next;
		Node* prev;
		for (int i = 1; i < pos; i++)
		{
			remove = remove->next;
		}
		printf("\n%d\n", remove->data);

		next = remove->next;
		prev = remove->prev;

		next->prev = prev;
		prev->next = next;

		myList->numberOfNodes--;

		free(remove);

	}
	else
	{
		printf("error!\n");
		system("pause");
	}
}
Beispiel #30
0
void WorkerThread::run( const Event* stopSignal )
{
    try
    {
        while ( WAIT_TIMEOUT == stopSignal->wait(10) )
        {
            if ( 0 == queueSize() )
                continue;
            WorkerThreadTask* t = getFirst();
            bool keepWorking = t->execute();
            removeFirst();
            delete t;
            if ( ! keepWorking )
            {
                break;
            }
        }
    }
    catch( ... )
    {
    }

}