ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) { int jump=0; ListNode *ln=NULL,*lncurr=NULL; while(l1 && l2){ int val=l1->val+l2->val+jump; jump=val/10; val=val%10; addNewNode(ln,lncurr,val); l1=l1->next;l2=l2->next; } while(l1){ int val=l1->val+jump; jump=val/10; val=val%10; addNewNode(ln,lncurr,val); l1=l1->next; } while(l2){ int val=l2->val+jump; jump=val/10; val=val%10; addNewNode(ln,lncurr,val); l2=l2->next; } if(jump>0){ addNewNode(ln,lncurr,jump); } return ln; }
int main() { first = NULL; last = NULL; addNewNode("Complete Project", "5/23/2012", "CIS4100", 5); addNewNode("Finish book", "7/30/2012", "Halfway in book two", 2); std::cout<<"----Traversing List----"<<std::endl; traverseNodes(); std::cout<<"----You just traversed the List----"<<std::endl; std::cin.ignore(); return 0; }
/** * Create new leaf nodes by copying the children of <code>parent</code> * TODO: Should let parent be const, but setting its index property to be able to rebuild the edge structure. * Do that in a preparation step instead. */ void TreeData::readFromSubNetwork(NodeBase* parent) { // Clone all nodes unsigned int numNodes = parent->childDegree(); reserveNodeCount(numNodes); unsigned int i = 0; for (NodeBase::sibling_iterator childIt(parent->begin_child()), endIt(parent->end_child()); childIt != endIt; ++childIt, ++i) { addNewNode(*childIt); // New node copies the data from the other childIt->index = i; // Set index to its place in this subnetwork to be able to find edge target below } // Clone edges for (NodeBase::sibling_iterator childIt(parent->begin_child()), endIt(parent->end_child()); childIt != endIt; ++childIt) { NodeBase& node = *childIt; for (NodeBase::edge_iterator outEdgeIt(node.begin_outEdge()), endIt(node.end_outEdge()); outEdgeIt != endIt; ++outEdgeIt) { EdgeType edge = **outEdgeIt; // If neighbour node is within the same cluster, add the link to this subnetwork. if (edge.target.parent == parent) { addEdge(node.index, edge.target.index, edge.data.weight, edge.data.flow); } // else flow out of sub-network } } }
MtpObjectHandle MtpStorage::beginSendObject(const char* path, MtpObjectFormat format, MtpObjectHandle parent, uint64_t size, time_t modified) { MTPD("MtpStorage::beginSendObject(), path: '%s', parent: %u, format: %04x\n", path, parent, format); iter it = mtpmap.find(parent); if (it == mtpmap.end()) { MTPE("parent node not found, returning error\n"); return kInvalidObjectHandle; } Tree* tree = it->second; std::string pathstr(path); size_t slashpos = pathstr.find_last_of('/'); if (slashpos == std::string::npos) { MTPE("path has no slash, returning error\n"); return kInvalidObjectHandle; } std::string parentdir = pathstr.substr(0, slashpos); std::string basename = pathstr.substr(slashpos + 1); if (parent != 0 && parentdir != getNodePath(tree)) { MTPE("beginSendObject into path '%s' but parent tree has path '%s', returning error\n", parentdir.c_str(), getNodePath(tree).c_str()); return kInvalidObjectHandle; } MTPD("MtpStorage::beginSendObject() parentdir: %s basename: %s\n", parentdir.c_str(), basename.c_str()); // note: for directories, the mkdir call is done later in MtpServer, here we just reserve a handle bool isDir = format == MTP_FORMAT_ASSOCIATION; Node* node = addNewNode(isDir, tree, basename); handleCurrentlySending = node->Mtpid(); // suppress inotify for this node while sending return node->Mtpid(); }
void TextUI::processCommand() { string choice; cin >> choice; switch(atoi(choice.c_str())) { case Load: loadERDiagram(); displayMenu(); break; case Save: saveERDiagram(); displayMenu(); break; case Add: addNewNode(); displayMenu(); break; case Connect: addConnection(); displayMenu(); break; case GetTable: displayComponentTable(); displayConnectionTable(); displayMenu(); break; case SetPK: setPrimaryKey(); displayMenu(); break; case GetERTable: displayERDiagramTable(); displayMenu(); break; case Delete: deleteComponent(); displayMenu(); break; case Undo: undoCmd(); displayMenu(); break; case Redo: redoCmd(); displayMenu(); break; case Exit: exitERDiagram(); break; default: cout << TEXT_MENU_ERRORCHOICE; displayMenu(); break; } }
void place(Queue* workQueue,QNode* node,int queue_size){ pthread_mutex_lock(&mtx);//protect data by locking the mutex while (workQueue->_size >= queue_size){ //printf(">>WorkQueue is full\n"); pthread_cond_wait(&cond_full,&mtx); } //printf("place to queue\n"); addNewNode(workQueue,node); pthread_mutex_unlock(&mtx); }
int main(){ struct node *ptr = initNode(6); addNewNode(ptr,3); addNewNode(ptr,4); addNewNode(ptr,4); addNewNode(ptr,3); addNewNode(ptr,6); // 634436 is a palindrome. printList(ptr); printf("Is a palindrome reverse: %s\n",isPalindromeReverse(ptr)); printf("Is a palindrome iterate: %s\n",isPalindromeIterate(ptr)); addNewNode(ptr,7); printList(ptr); printf("Is a palindrome reverse: %s\n",isPalindromeReverse(ptr)); printf("Is a palindrome iterate: %s\n",isPalindromeIterate(ptr)); }
/* ===== process ===== This function presents the user with the menu. Pre hash, list, tree Post nothing */ void process (HASH *hash, D_LIST *list, BST_TREE *tree) { // Local Definitions char choice; CAR car; // Statements do { choice = getChoice (); switch (choice) { case 'P': printHash(hash); printLinkedList(list); printManager(tree); break; case 'R': printIndentedBST(tree); break; case 'E': printData(hash); break; case 'S': searchByHash(hash, list); break; case 'T': searchByDList(list); break; case 'I': car = addNewNode(); insert(hash,car); insertDNode(list, car); insertTree(tree,car); break; case 'D': deleteCar(list, hash, tree); break; case 'W': writeToFile(list); break; case 'Q': break; } // switch } while (choice != 'Q'); return; } // process
int MtpStorage::readDir(const std::string& path, Tree* tree) { struct dirent *de; int storageID = getStorageID(); MtpObjectHandle parent = tree->Mtpid(); DIR *d = opendir(path.c_str()); MTPD("reading dir '%s', parent handle %u\n", path.c_str(), parent); if (d == NULL) { MTPE("error opening '%s' -- error: %s\n", path.c_str(), strerror(errno)); return -1; } // TODO: for refreshing dirs: capture old entries here while ((de = readdir(d)) != NULL) { // Because exfat-fuse causes issues with dirent, we will use stat // for some things that dirent should be able to do std::string item = path + "/" + de->d_name; struct stat st; if (lstat(item.c_str(), &st)) { MTPE("Error running lstat on '%s'\n", item.c_str()); return -1; } // TODO: if we want to use this for refreshing dirs too, first find existing name and overwrite if (strcmp(de->d_name, ".") == 0) continue; if (strcmp(de->d_name, "..") == 0) continue; Node* node = addNewNode(st.st_mode & S_IFDIR, tree, de->d_name); node->addProperties(item, storageID); //if (sendEvents) // mServer->sendObjectAdded(node->Mtpid()); // sending events here makes simple-mtpfs very slow, and it is probably the wrong thing to do anyway } closedir(d); // TODO: for refreshing dirs: remove entries that no longer exist (with their nodes) tree->setAlreadyRead(true); addInotify(tree); return 0; }
int processApi(unsigned char *buf, int len) { int i; zbTxStatusResponse_t *txStatus; node_t *node; nodeIdentification_t *nodeId; switch(buf[0]) { case ZB_TX_API_CMD: printf("I spy a Zigbee packet transmission -> "); break; case ZB_RX_API_CMD: if(len < 12) break; switch(buf[12]) { case QUERY_TIME_SENSOR_CMD | 0x80: printf("Retrieved time: %u\n", *(unsigned int *)&buf[13]); return 0; break; case QUERY_SENSOR_SENSOR_CMD | 0x80: { struct querySensorResponse *sensor = (struct querySensorResponse *)&buf[12]; int num = sensor->sensor; int type = sensor->type; time_t time = sensor->time; int val = sensor->data16[0]; int val2 = sensor->data16[1]; node = findNodeByAddr64((macAddr64_t *)&buf[1]); if(node != NULL) { if(type == 3) printf("Sensor(%d) on %s is %.2f°F and %.2f%% humidity @ %lu\n", num, node->identifier, ((double)val / (double)(1 << 14) * 165. - 40.) * 9./5. + 32., (double)val2 / (double)(1 << 14) * 100., time); else if(type == 6) printf("Sensor(%d) on %s is at %.2f%% of light @ %lu\n", num, node->identifier, (double)val / (double)(1 << 15) * 100., time); else printf("Sensor(%d) on %s is %.2f°F @ %lu\n", num, node->identifier, (double)(val - (273 << 4)) * 0.0625 * 9./5. + 32., time); } //temp = (double)val / (double)(1 << 14) * 165. - 40.; } return 0; break; case DEBUG_SENSOR_CMD: printf("Debug: '"); fflush(stdout); buf += 13; len -= 13; while(len-- > 0) { if(isprint(*buf)) { printf("%c", *buf++); } else { printf("<%02X>", (unsigned)*buf++); } } printf("'\n"); return 0; break; default: printf("Unknown command: 0x%x\n", buf[12]); } if(len == 16) { printf("Retrieved time: %u\n", *(unsigned int *)&buf[12]); return 0; } printf("I spy a Zigbee packet reception -> "); for(i = 12; i < len; i++) fputc(buf[i], stdout); fputc('\n', stdout); return 0; break; case AT_API_CMD: printf("I spy an AT command -> "); break; case AT_RESP_API_CMD: printf("I spy an AT command response -> "); break; case ZB_TX_STATUS_API_CMD: txStatus = (zbTxStatusResponse_t *)buf; printf("TX Status report: "); if(txStatus->deliveryStatus != ZB_DELIVERY_STATUS_SUCCESS) { printf("Failed to transmit packet: 0x%x\n", txStatus->deliveryStatus); } else { printf("Success with %d retries.\n", txStatus->retries); } return 0; break; case NODE_IDENTIFICATION_API_CMD: nodeId = (nodeIdentification_t *)buf; //printf("I spy a node identification -> %s\n", nodeId->identifier); //(char *)&buf[22]); addNewNode(nodeId); addNewNodeCallback(nodeId); return 0; break; default: /* Ignore unknown commands */ printf("Unknown API Packet: 0x%x -> ", buf[0]); break; } buf++; printf("P: '"); while(len-- > 0) { if(isprint(*buf)) { printf("%c", *buf++); } else { printf("<%02X>", (unsigned)*buf++); } } printf("'\n"); return 0; }
void MtpStorage::handleInotifyEvent(struct inotify_event* event) { std::map<int, Tree*>::iterator it = inotifymap.find(event->wd); if (it == inotifymap.end()) { MTPE("Unable to locate inotify_wd: %i\n", event->wd); return; } Tree* tree = it->second; MTPD("inotify_t tree: %x '%s'\n", tree, tree->getName().c_str()); Node* node = tree->findEntryByName(basename(event->name)); if (node && node->Mtpid() == handleCurrentlySending) { MTPD("ignoring inotify event for currently uploading file, handle: %u\n", node->Mtpid()); return; } if (event->mask & IN_CREATE || event->mask & IN_MOVED_TO) { if (event->mask & IN_ISDIR) { MTPD("inotify_t create is dir\n"); } else { MTPD("inotify_t create is file\n"); } if (node == NULL) { node = addNewNode(event->mask & IN_ISDIR, tree, event->name); std::string item = getNodePath(tree) + "/" + event->name; node->addProperties(item, getStorageID()); mServer->sendObjectAdded(node->Mtpid()); } else { MTPD("inotify_t item already exists.\n"); } if (event->mask & IN_ISDIR) { // TODO: do we need to do anything here? probably not until someone reads from the dir... } } else if (event->mask & IN_DELETE || event->mask & IN_MOVED_FROM) { if (event->mask & IN_ISDIR) { MTPD("inotify_t Directory %s deleted\n", event->name); } else { MTPD("inotify_t File %s deleted\n", event->name); } if (node) { if (event->mask & IN_ISDIR) { for (std::map<int, Tree*>::iterator it = inotifymap.begin(); it != inotifymap.end(); ++it) { if (it->second == node) { inotify_rm_watch(inotify_fd, it->first); MTPD("inotify_t removing watch on '%s'\n", getNodePath(it->second).c_str()); inotifymap.erase(it->first); break; } } } MtpObjectHandle handle = node->Mtpid(); deleteFile(handle); mServer->sendObjectRemoved(handle); } else { MTPD("inotify_t already removed.\n"); } } else if (event->mask & IN_MODIFY) { MTPD("inotify_t item %s modified.\n", event->name); if (node != NULL) { uint64_t orig_size = node->getProperty(MTP_PROPERTY_OBJECT_SIZE).valueInt; struct stat st; uint64_t new_size = 0; if (lstat(getNodePath(node).c_str(), &st) == 0) new_size = (uint64_t)st.st_size; if (orig_size != new_size) { MTPD("size changed from %llu to %llu on mtpid: %u\n", orig_size, new_size, node->Mtpid()); node->updateProperty(MTP_PROPERTY_OBJECT_SIZE, new_size, "", MTP_TYPE_UINT64); mServer->sendObjectUpdated(node->Mtpid()); } } else { MTPE("inotify_t modified item not found\n"); } } else if (event->mask & IN_DELETE_SELF || event->mask & IN_MOVE_SELF) { // TODO: is this always already handled by IN_DELETE for the parent dir? } }
int compress(const char *sourceFile, const char *resultFile) { /* ====================================== Открываем файл ====================================== */ FILE *source = fopen(sourceFile, "rb"); if (source == NULL) return -1; //Error: couldn't open source file /* ====================================== Считаем встречаемость символов (веса) ====================================== */ long weights[256] = {0}; //Q&A //Q: Почему используется не char, а unsigned char? //A: Потому что в char русские символы записывались с отрицательными кодами. //Q: Почему символ читается сначала в tmpCh, а затем в sourceCh? //A: При чтении EOF символа в unsigned char получается не -1, а 255 (знака ведь нет!) //Q: Почему мы используем int, а не char в качестве типа темповой переемнной. //A: Всё дело в том, что при использовании char, символ 'я' будет иметь такой же код, как и EOF. int tmpCh = 0; unsigned char sourceCh = 0; while ((tmpCh = fgetc(source)) != EOF) { sourceCh = tmpCh; weights[sourceCh]++; } /* ===================================== Формируем массив нод ===================================== */ //Массив нод node *nodeArray = NULL; int nodesCount = 0; //Заполняем массив начальными нодами for (int i = 0; i < 256; i++) { //Пропускаем все ноды с нулевым весом if (weights[i] == 0) continue; //Новый нод node newNode = createNewNode(i, weights[i], -1, -1); //Добавляем нод addNewNode(nodeArray, nodesCount, newNode); } /* ====================================== Заполняем дерево родительскими нодами ====================================== */ // Дерево (массив указателей на структуры) node *tree = NULL; int leavesCount = 0; //Пока в массиве нод ещё есть ноды, заполняем дерево их копиями в памяти while (nodesCount > 1) { //Сортируем массив нод в зависимости от веса элементов qsNodeArray(nodeArray, 0, nodesCount - 1); //Берём два первых нода (с минимальными весам) node nMin1 = *(nodeArray); node nMin2 = *(nodeArray + 1); //Добавляем указатели на них в дерево addNewNode(tree, leavesCount, nMin1); //leavesCount - 2 addNewNode(tree, leavesCount, nMin2); //leavesCount - 1 //Из них получаем новый нод node newNode = createNewNode('\0', nMin1.weight + nMin2.weight, leavesCount - 2, leavesCount - 1); //Добавляем получившийся нод в массив нод addNewNode(nodeArray, nodesCount, newNode); //Удаляем ноды nMin1 и nMin2 из массива нод: мы уже их использовали deleteNode(nodeArray, nodesCount, 0); deleteNode(nodeArray, nodesCount, 0); //Второй сместился на первый, поэтому опять удаляем первый } //На этом этапе в массиве нод (nodesArray) остаётся один нод (nodesCount == 1) //Этот нод как раз и будет root-нодом! node rootNode = *(nodeArray); //С массивом нод покончено. Он нам больше не пригодится. Теперь работаем с деревом free(nodeArray); //Добавляем root-нод в дерево addNewNode(tree, leavesCount, rootNode); /* ====================================== Создаём массив представлений символов ====================================== */ //Массив представлений символов (индекс - код символа, huffmanCh.bits - последовательность бит, определяющая его) //Таблица соответствий huffmanCh codesArr[256]; //Темповый объект, используется функцией сreateCodesArray для хранения кода символа, обнуляем его huffmanCh *symbolCode = (huffmanCh *)malloc(sizeof(huffmanCh)); memset(symbolCode, 0, sizeof(huffmanCh)); //Создаём таблицу соответствий createCodesArray(codesArr, tree, rootNode, -1, symbolCode); /* ====================================== Открываем файл-результат на запись ====================================== */ FILE *result = fopen(resultFile, "wb"); if (result == NULL) return -2;//Error: couldn't open result file /* ====================================== Пишем дерево в файл ====================================== */ //Сначала запишем, сколько нодов в дереве fwrite(&leavesCount, sizeof(int), 1, result); //Далее пишем само дерево fwrite(tree, sizeof(node), leavesCount, result); /* ====================================== Запись закодированной информации ====================================== */ //Посимвольно проходимся по source-файлу rewind(source); //Перемещаемся на начало файла int tmpCh_ = 0; //Текущий символ unsigned char resultCh = 0; //Закодированный байт char codedChar = 0; //Текущий бит unsigned char currBit = 0; //Текущий элемент в строке бит текущего символа unsigned char currBitInCode = 0; while ((tmpCh_ = fgetc(source)) != EOF) { resultCh = tmpCh_; while (currBitInCode < codesArr[resultCh].bitsCount) { switch (codesArr[resultCh].bits[currBitInCode]) { case 1: codedChar |= (1<<(7 - currBit)); //Устанавливаем текущий бит в единицу break; case 0: codedChar &= ~(1<<(7 - currBit)); //Устанавливаем текущий бит в ноль break; } //Если мы записали последний бит if (currBit == 7) { //Пишем в файл закодированный байт fwrite(&codedChar, sizeof(char), 1, result); //Обнуляем, чтобы затем начать с первого бита нового байта currBit = 0; codedChar = 0; //Если мы не дописали представление текущего символа, //то переходим к следующему элементу его строки бит и начинаем цикл сначала if (++currBitInCode < codesArr[resultCh].bitsCount) continue; else //Иначе выходим из цикла break; } currBitInCode++; currBit++; } currBitInCode = 0; } char lastByteBitsCount = 8; // Количество значимых бит в последнем байте зашифрованной информации //Если мы не дописали сколько-то бит if (currBit > 0) { //Меняем количество значимых бит lastByteBitsCount = currBit; //Не нужно прибавлять один к currBit, потому что в цикле уже прибавили //Дописываем последний байт зашифрованной информации fwrite(&codedChar, sizeof(char), 1, result); } //Дописываем самый последний байт файла - количество значимых бит в последнем байте зашифрованной информации fwrite(&lastByteBitsCount, sizeof(char), 1, result); //В дереве больше нет необходимости free(tree); //Вот теперь можно закрыть файлы fclose(source); fclose(result); return 1; //File has been succefully compressed }
void remember(AST t) { headptr = addNewNode(headptr, t); }