/* Driver program to test above functions */
int main()
{
  int list_size, i;

  /* Initialize lists as empty */
  struct node *head = NULL;
  struct node *head1 = NULL;
  struct node *head2 = NULL;

  /* Created linked list will be 12->56->2->11 */
  push(&head, 12);
  push(&head, 56);
  push(&head, 2);
  push(&head, 11);

  printf("Original Circular Linked List");
  printList(head);

  /* Split the list */
  splitList(head, &head1, &head2);

  printf("\nFirst Circular Linked List");
  printList(head1);

  printf("\nSecond Circular Linked List");
  printList(head2);

  getchar();
  return 0;
}
Example #2
0
MVJSONNode* MVJSONReader::parse(string text)
{
	string s = trim(text);
	if (s.length() < 2) return NULL;

	// object
	if ((s[0] == '{') && (s[s.length() - 1] == '}'))
	{
		// erase last and first symbols
		s.erase(0, 1);
		s.erase(s.length() - 1, 1);

		vector<string> parts;
		splitList(s, parts);

		MVJSONNode* node = new MVJSONNode();

		for (int i = 0; i < parts.size(); i++)
			node->values.push_back(parseValue(parts.at(i), false));

		return node;
	}

	return NULL;
}
Example #3
0
/*Driver program to test above functions*/
int main()
{
	int list_size, i ;

	/*Intialize list as empty*/
	struct node *head = NULL ;
	struct node *head1 = NULL ;
	struct node *head2 = NULL ;

	/*Created link list 1->2->3->4->5*/
	push(&head,1) ;
	push(&head,2) ;
	push(&head,3) ;
	push(&head,4) ;
	//push(&head,5) ;

	printf("\nCircular List Before Split\n");
	printList(head);

	/*Let's Split the list */
	splitList(head,&head1,&head2);

	printf("\nFirst Circular Linked List\n");
	printList(head1);

	printf("\nSecond Circular Linked List\n");
	printList(head2);

	return 0 ;


}
Example #4
0
MVJSONValue* MVJSONReader::parseValue(string text, bool hasNoName)
{
	string key;
	string s;
	splitInHalf(text, ":", key, s);
	key = trim(key);
	s = trim(s);
	if (key.length() > 2)
	{
		// strip "
		key.erase(0, 1);
		key.erase(key.length() - 1, 1);
	}

	if (hasNoName)
	{
		s = text;
		key = "";
	}


	if (s == "false") // bool
		return new MVJSONValue(key, false);

	if (s == "true")  // bool
		return new MVJSONValue(key, true);

	if (s == "null") // null
		return new MVJSONValue(key, MVJSON_TYPE_NULL);

	char first = s[0];

	if (first == '"') // string
		return new MVJSONValue(key, s.substr(1, s.length() - 2));

	if (first == '{') // object
		return new MVJSONValue(key, parse(s));

	if (first == '[') // array
	{
		s.erase(0, 1);
		s.erase(s.length() - 1, 1);
		vector<string> parts;
		splitList(s, parts);

		MVJSONValue* val = new MVJSONValue(key, MVJSON_TYPE_ARRAY);
		for (int i = 0; i < parts.size(); i++)
			val->arrayValue.push_back(parseValue(parts.at(i), true));
		return val;
	}

	// else its number!
	if (s.find(".") == string::npos)
		return new MVJSONValue(key, stringToInt(s));
	else
		return new MVJSONValue(key, stringToDouble(s));

}
Example #5
0
	ListNode * mergeSort( ListNode * head )
	{
		if ( ! head || ! head->next )
			return head;
		
		ListNode * mid = splitList( head );
		ListNode * h1 = mergeSort( head );
		ListNode * h2 = mergeSort( mid );
		return merge( h1, h2 );
	}
Example #6
0
 ListNode* sortList(ListNode* head) {
     if(head==NULL||head->next==NULL)
         return head;
     ListNode *temp1,*t1,*t2;
     temp1=head;
     splitList(temp1,&t1,&t2);
     t1=sortList(t1);
     t2=sortList(t2);
     head=mergeTwoLists(t1,t2);
     return head;
 }
Example #7
0
    ListNode *sortList(ListNode *head) {

        ListNode *head2;
        if (!head || !head->next)
        {// if the list is empty or only has one node, just return
            return head;
        }
        else
        {// split the list by half, sort each of them and merge the two half lists
            head2 = splitList(head);
            return mergeList(sortList(head), sortList(head2));
        }
    }
Example #8
0
static listnode_t *doMergeSort(listnode_t *list, comparefunc funcCompare)
{
    listnode_t *p;

    if(list->next)
    {
        p = splitList(list);

        // Sort both halves and merge them back.
        list = mergeLists(doMergeSort(list, funcCompare),
                          doMergeSort(p, funcCompare), funcCompare);
    }
    return list;
}
 vector<ListNode*> splitListToParts(ListNode* root, int k) {
     int n = 0;
     ListNode *p1;
     p1 = root;
     while (p1 != NULL) {
         p1 = p1->next;
         ++n;
     }
     
     int m = n / k;
     int k1 = n % k;
     int k2 = k - k1;
     vector<ListNode *> res;
     
     int i;
     for (i = 0; i < k1; ++i) {
         splitList(root, res, m + 1);
     }
     for (i = 0; i < k2; ++i) {
         splitList(root, res, m);
     }
     return res;
 }
Example #10
0
void mergeSortForList(LNode** phead) {
	LNode* head = *phead;
	LNode* a;
	LNode* b;

	if (head == NULL || head->next == NULL)
		return;

	splitList(head, &a, &b);
	
	mergeSortForList(&a);
	mergeSortForList(&b);

	*phead = sortMerge(a, b);
}
Example #11
0
File: prob.c Project: da-x-ace/Misc
void mergeSort(struct node** head)
{
	struct node* tmp = *head;
	struct node* a = null;
	struct node* b = null;
	
	if(tmp == null || tmp->next == null)
		return;
	
	splitList(tmp, &a,&b);
	
	mergeSort(&a);
	mergeSort(&b);
	
	*head = mergeList(a, b);
		
}
Example #12
0
int main() {
	struct node *evenList, *oddList;
	int listarr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
	struct node *list = constructIntList(listarr, ARRAY_SIZE(listarr));
	printf("Original List :");
	printList(list);
	splitList(list, &evenList, &oddList);
	printf("Even List : ");
	printList(evenList->next);
	printf("Odd List : ");
	printList(oddList->next);
	printf("Final List : ");
	struct node *finalList = joinList(evenList, oddList);
	printList(finalList);
	freeList(finalList);
	free(evenList);
	free(oddList);
	return 0;
}
Example #13
0
void
SoAction::splitPathList(const SoPathList &sortedList,
			const SoPathList &origPathList)
//
////////////////////////////////////////////////////////////////////////
{
    int		numPaths, curStart, i;
    SoNode	*curHead;

    numPaths = sortedList.getLength();

    // Create a list to hold one of the split lists
    SoPathList	splitList(numPaths);

    // Split list while there are still paths to examine
    curStart = 0;
    while (curStart < numPaths) {

	// Gather all paths with same head
	curHead = sortedList[curStart]->getHead();
	splitList.append(sortedList[curStart]);

	for (i = curStart + 1; i < numPaths; i++) {
	    if (sortedList[i]->getHead() != curHead)
		break;
	    splitList.append(sortedList[i]);
	}

	// Apply action to split list. Indicate that it's the last
	// path list if there are no more paths after these.
	apply(splitList, origPathList, i >= numPaths);

	// Prepare for next set of paths
	splitList.truncate(0);
	curStart = i;
    }
}
Example #14
0
/* smallShell
 *
 * smallShell innehåller logiken för shellets funktionalitet som definierat
 * i laborationsbeskrivningen.
 *
 */
void
smallShell()
{
    char arg[70] = ""; /* Hanterare för argument */
    signal(SIGINT, signalHandler); /* Hantera CTRL-C */

    int isBackground;
    while(1) /* Evighetsloop då programmet endast ska avlutas vid "exit" */    
    {
        printf("==>> "); /* Skriv ut prompttecken */
        
        /* Rensa zombieprocesser */
		bgChildProcesses = zombieFilter(bgChildProcesses, &terminationCheck);
        
        fgets(arg, 70, stdin); /* Hämta argument från stdin till arg */
        char **args = splitList(arg, 0); /* Dela in indatat i lista */

        char *command = args[0]; /* Det första argumentet är kommandot */
        if(command != NULL)
        {
            /* Kolla om inbyggt kommando */
            if(!strcmp(command, "exit")) {
                free(args);
                return;
            } else if(!strcmp(command, "cd")) {
                if(chdir(args[1])) {
                    chdir(getenv("HOME"));
                }
            } else { /* Icke inbyggt kommando */
				execProgram(args);
            }
        }
        
        free(args);
    } 
}
Example #15
0
int main(int argc, char **argv) {
	dlist *list;
	dlist *list2;
	dlist *list3;
	dlist *list4;
	int choice;
	int i = 0;
	int numData;
	Node *p;
	FILE *fin, *fout;
	int select = 0;
	int startFrom, numSplit; // where to split and the length of splitting list
	char fileName[15]; //file name for output data
	char textName1[20], textName2[20]; // file name for split lists

	char sections [MAX][40] = {"Import from phonebook.dat", "Display (traverse)", "Add new contact (insert before/after)",
	                           "Insert a position" , "Delete a position", "Delete current",
	                           "Delete first", "Search and Update", "Divide and Extract",
	                           "Reverse list", "Save to file", "Count max identical phone numbers", "Exit (free)"
	                          };


	do {
		choice = getMenu(sections, MAX);
		switch (choice) {
		case 1:

			// if ((fin = fopen(argv[1], "r")) == NULL)
			// {
			// 	printf("Can't open file %s\n", argv[1]);
			// 	exit(1);
			// }
			// if ((fout = fopen(argv[2], "wb")) == NULL)
			// {
			// 	printf("Can't open file %s\n", argv[2]);
			// 	exit(1);
			// }

			// numData = importDB(fin, fout);

			// fclose(fin);
			// fclose(fout);

			list = iniList(list);
			list2 = iniList(list2);
			list3 = iniList(list3);
			list4 = iniList(list4);
			if ((fin = fopen(argv[1], "rb")) == NULL)
			{
				printf("Can't open file %s\n", argv[1]);
				exit(1);
			}
			fseek(fin, 0, SEEK_END);
			numData = ftell(fin) / sizeof(element_type);
			rewind(fin);
			result = import(fin, numData);
			for (i = 0; i < result; ++i)
				insertEnd(contact[i], list);
			// printData();
			fclose(fin);
			break;
		case 2:
			traverse(list);
			break;
		case 3:
			printf("Enter 0 to insert before, 1 to insert after: ");
			scanf("%d", &select);
			while (getchar() != '\n');
			if (select == 0)
				insertBefore(list->root, typeHand(), list);
			else
				insertEnd(typeHand(), list);
			break;
		case 4: printf("Position to insert after (1 means root element): ");
			scanf("%d", &select);
			printf("Type in the data to insert\n");
			while (getchar() != '\n');
			if (select < numData)
				insertAfter(locateNode(select, list), typeHand(), list);
			else
				insertEnd(typeHand(), list);
			break;
		case 5: printf("Position to delete: (1 means root element)");
			scanf("%d", &select);
			delNode(locateNode(select, list), list);
			break;
		case 6: delNode(list->cur, list);
			break;
		case 7: delNode(list->root, list);
			break;
		case 8: searchName();
			while (1) {

				printf("Update for position number (type -1 to stop updating): ");
				scanf("%d", &select);
				while (getchar() != '\n');
				if (select == -1)
					break;

				insertAfter(locateNode(select, list), typeHand(), list);
				delNode(locateNode(select, list), list);
				printf("Update success\n");
			}
			break;
		case 9:
			printf("The length of the list is %d\n", listLength(list));
			printf("Type in where to start (range from 1 to end of the list): ");
			scanf("%d", &startFrom);
			printf("Length of spliting: ");
			scanf("%d", &numSplit);
			if (listLength(list) > startFrom + numSplit)
				splitList(startFrom, numSplit, list, list2, list3);
			else
				splitList(startFrom, listLength(list) - startFrom, list, list2, list3);
			while (getchar() != '\n');
			printf("Now type in 2 file name to save the new lists\n");
			printf("File 1: ");
			scanf("%s", textName1);
			printf("File 2: ");
			scanf("%s", textName2);
			checkList(list2, textName1); //result of splitList
			checkList(list3, textName2);
			break;
		case 10:
			reverseList(list);
			break;
		case 11:
			printf("Type in the file name\n");
			scanf("%s", fileName);
			if ((fout = fopen(fileName, "w + t")) == NULL)
			{
				printf("Can't open file %s\n", fileName);
				exit(1);
			}
			savetoFile(fout, list);
			break;
		case 12:
			list4 = countsameNum(list, list4);
			printf("After spliting, the new list with identical numbers: \n");
			p = list4->root;
			while ( p != NULL ) {
				printf("Node with phone number: %s, address %p\n", p->element.tel, p);
				p = p->next;
			}
			break;
		case MAX:
			freeList(list);
			freeList(list2);
			freeList(list3);
			freeList(list4);
			exit(1);
			break;
		default: printf("Invalid choice. It must be from 1 to %d\n", MAX); break;
		}
	} while (choice != MAX);
	return 0;
}
Example #16
0
bool
SrmDevice::download( const QDir &tmpdir,
                    QList<DeviceDownloadFile> &files,
                    QString &err)
{
    srmio_error_t serr;
    struct _srmio_pc_xfer_block_t block;
    srmio_data_t data( NULL );
    srmio_data_t *splitList( NULL );
    srmio_data_t *split;
    int mfirst( -1 );
    size_t block_cnt, block_num( 0 );
    size_t prog_sum( 0 ), prog_prev( 0 );
    size_t chunks_done( 0 );
    srmio_time_t splitGap( 72000 ); // 2h - NOTE: we could make this configurable

    if( ! is_open ){
        if( ! open( err ) )
            return false;
    }

    // fetch preview in case user didn't
    if( srmio_pc_can_preview(pc) && rideList.size() == 0 ){
        if( ! preview( err ) )
            return false;
    }

    data = srmio_data_new( &serr );
    if( ! data ){
        err = tr("failed to allocate data handle: %1")
            .arg(serr.message);
        goto fail;
    }

    if( m_Cancelled ){
        err = tr("download cancelled");
        goto fail;
    }

    if( ! srmio_pc_xfer_start( pc, &serr )){
        err = tr("failed to start download: %1")
            .arg(serr.message);
        goto fail;
    }

    if( ! srmio_pc_xfer_get_blocks( pc, &block_cnt, &serr ) ){
        err = tr("failed to get number of data blocks: %1")
            .arg(serr.message);
        goto fail1;
    }

    for( int i = 0; i < rideList.size(); ++i ){
        if( rideList.at(i)->wanted )
            prog_sum += rideList.at(i)->work;
    }

    while( srmio_pc_xfer_block_next( pc, &block )){
        bool wanted = false;
        struct _srmio_chunk_t chunk;
        bool is_int;
        bool is_first;
        size_t prog_total;

        if( rideList.empty() ){
            wanted = true;

        } else {
            for( int i = 0; i < rideList.size(); ++i ){
                if( rideList.at(i)->startTime.toTime_t() == block.start / 10 ){
                    wanted = rideList.at(i)->wanted;
                    break;
                }
            }
        }

        if( ! wanted ){
            emit updateStatus(tr("skipping unselected ride block %1")
                .arg(block_num +1));
            ++block_num;
            continue;
        }

        data->slope = block.slope;
        data->zeropos = block.zeropos;
        data->circum = block.circum;
        if( block.athlete ){
            if( data->athlete )
                free( data->athlete );
            data->athlete = strdup( block.athlete );
        }

        if( ! rideList.empty() ){
            prog_total = prog_sum;

        } else if( block_cnt == 1 ){
            prog_total = block.total;

        } else {
            prog_total = block_cnt * 1000;
        }

        while( srmio_pc_xfer_chunk_next( pc, &chunk, &is_int, &is_first  ) ){
            if( m_Cancelled ){
                err = tr("download cancelled");
                goto fail1;
            }

            if( chunks_done % 16 == 0 ){
                size_t block_done;

                srmio_pc_xfer_block_progress( pc, &block_done );
                if( ! rideList.empty() ){
                    block_done += prog_prev;

                } else if( block_cnt == 1 ){
                    // unchanged

                } else {
                    block_done = (double)block_num * 1000
                        + 1000 * block.total / block_done;
                }

                emit updateProgress( tr("progress: %1/%2")
                    .arg(block_done)
                    .arg(prog_total));
            }

            if( ! srmio_data_add_chunk( data, &chunk, &serr ) ){
                err = tr("adding chunk failed: %1")
                    .arg(serr.message);
                goto fail1;
            }

            ++chunks_done;

            /* finish previous marker */
            if( mfirst >= 0 && ( ! is_int || is_first ) )
                if( ! srmio_data_add_marker( data, mfirst, data->cused -2, &serr ) ){
                    err = tr("adding marker failed: %1")
                        .arg(serr.message);
                    goto fail1;
                }

            /* start marker */
            if( is_first ){
                mfirst = (int)data->cused -1;

            } else if( ! is_int ){
                mfirst = -1;

            }
        }

        /* finalize marker at block end */
        if( mfirst >= 0 ){
            if( ! srmio_data_add_marker( data, mfirst, data->cused -1, &serr ) ){;
                err = tr("adding marker failed: %1")
                  .arg(serr.message);
                goto fail1;
            }
            mfirst = -1;
        }

        if( ! rideList.empty() )
            prog_prev += block.total;
        else
            prog_prev += 1000;

        if( block.athlete )
            free( block.athlete );
        block.athlete = NULL;

        ++block_num;
    }

    if( srmio_pc_xfer_state_success != srmio_pc_xfer_status( pc, &serr ) ){
        err = tr( "download failed: %1")
            .arg(serr.message);
        goto fail;
    }

    if( ! srmio_pc_xfer_finish( pc, &serr ) ){
        err = tr( "download failed: %1")
            .arg(serr.message);
        goto fail;
    }

    emit updateStatus( tr("got %1 records").arg(data->cused) );

    if( m_Cancelled ){
        err = tr("download cancelled");
        goto fail;
    }

    if( ! data->cused ){
        err = tr("no data available");
        goto fail;
    }

    splitList = srmio_data_split( data, splitGap, 1000, &serr );
    if( ! splitList ){
        err = tr("Couldn't split data: %1")
            .arg(serr.message);
        goto fail;
    }

    for( split = splitList; *split; ++split ){
        FILE *fh( NULL );
        srmio_time_t stime;
        srmio_data_t fixed;
        DeviceDownloadFile file;

        // skip empty hunks ... shouldn't happen, just to be safe
        if( ! (*split)->cused ){
            continue;
        }

        fixed = srmio_data_fixup( *split, &serr );
        if( ! fixed ){
            err = tr("Couldn't fixup data: %1")
                .arg(serr.message);
            goto fail;
        }

        // skip empty hunks ... shouldn't happen, just to be safe
        if( ! fixed->cused ){
            srmio_data_free(fixed);
            continue;
        }

        file.extension = "srm";
        if (!get_tmpname(tmpdir, file.name, err))
            goto fail;

        if( ! srmio_data_time_start( fixed, &stime, &serr ) ){
            srmio_data_free(fixed);
            err = tr("Couldn't get start time of data: %1")
                .arg(serr.message);
            goto fail;
        }
        file.startTime.setTime_t( 0.1 * stime );

        fh = fopen( file.name.toAscii().constData(), "wb" );
        if( ! fh ){
            srmio_data_free(fixed);
            err = tr( "failed to open file %1: %2")
                .arg(file.name)
                .arg(strerror(errno));
            goto fail;
        }

        if( ! srmio_file_srm7_write(fixed, fh, &serr) ){
            srmio_data_free(fixed);
            err = tr("Couldn't write to file %1: %2")
                .arg(file.name)
                .arg(serr.message);
            fclose(fh);
            goto fail;
        }

        files.append(file);

        fclose( fh );
        srmio_data_free(fixed);

    }

    for( split = splitList; *split; ++split )
        srmio_data_free( *split );
    free(splitList);

    srmio_data_free( data );
    return true;

fail1:
    srmio_pc_xfer_finish(pc, NULL);

fail:
    if( data ) srmio_data_free( data );
    if( splitList ){
        for( split = splitList; *split; ++split )
            srmio_data_free( *split );
        free(splitList);
    }
    close();
    return false;
}
std::map<std::string, std::string> SaveDiffFittingAscii::validateInputs() {
  std::map<std::string, std::string> errors;

  bool is_grp = true;

  // check for null pointers - this is to protect against workspace groups
  const std::string inputWS = getProperty("InputWorkspace");

  WorkspaceGroup_sptr inWks =
      AnalysisDataService::Instance().retrieveWS<WorkspaceGroup>(inputWS);
  API::WorkspaceGroup_const_sptr inGrp =
      boost::dynamic_pointer_cast<const API::WorkspaceGroup>(inWks);

  const ITableWorkspace_sptr tbl_ws = getProperty("InputWorkspace");
  if (tbl_ws) {
    is_grp = false;
  }

  if (!inGrp && !tbl_ws) {
    std::string message =
        "The current version of this algorithm only "
        "supports input workspaces of type TableWorkspace and WorkspaceGroup";
    errors["InputWorkspace"] = message;
  }

  const std::string file = getProperty("Filename");
  if (file.empty()) {
    errors["Filename"] = "File name directory cannot be empty";
  }

  std::string runNumber = getPropertyValue("RunNumber");
  std::vector<std::string> splitRunNum = splitList(runNumber);

  std::string bankNumber = getPropertyValue("Bank");
  std::vector<std::string> splitBank = splitList(bankNumber);

  if (bankNumber.empty()) {
    if (!runNumber.empty())
      errors["Bank"] = "Please provide a valid bank list";
  } else if (runNumber.empty()) {
    errors["RunNumber"] = "Please provide a valid run number list";
  } else if (!is_grp) {
    if (splitRunNum.size() > 1) {
      errors["RunNumber"] = "One run number should be provided when a Table"
                            "workspace is selected";
    }
    if (splitBank.size() > 1) {
      errors["Bank"] = "One bank should be provided when a Table"
                       "Workspace is selected";
    }
  } else {
    if (splitRunNum.size() != inGrp->size()) {
      errors["RunNumber"] = "Run number list size should match the number of "
                            "TableWorkspaces in the GroupWorkspace selected";
    }
    if (splitBank.size() != inGrp->size()) {
      errors["Bank"] = "Bank list size should match the number of "
                       "TableWorkspaces in the GroupWorkspace selected";
    }
  }

  return errors;
}