按模反转字符串

2019-04-13 14:01发布

按模反转字符串,如123456,按模2反转,则输出为214365,按模3反转,则为321654,按模4,则是432165 //Reverse the node link typedef struct linknode{ int data; struct linknode* next; }node; node* ReverseLinkNode(node* head) { node*previous = head; node*q = head->next; head->next = NULL; while(NULL != q) { node*tmp = q->next; q->next = previous; previous = q; q = tmp; } head = previous; return head; } void test_reverse_string_as_mode() { //Node link via hard code here node*head = (node*)malloc(sizeof(node)); head->data = 1; node*node1 = (node*)malloc(sizeof(node)); node1->data = 2; head->next = node1; node*node2 = (node*)malloc(sizeof(node)); node2->data = 3; node1->next = node2; node*node3 = (node*)malloc(sizeof(node)); node3->data = 4; node2->next = node3; node*node4 = (node*)malloc(sizeof(node)); node4->data = 5; node3->next = node4; node*node5 = (node*)malloc(sizeof(node)); node5->data = 6; node5->next = NULL; node4->next = node5; node*p = head; const int k = 2; //mode,k >=2 const int ilength = 6; //linknode size int i = 0; node*new_link = NULL; node*tpm_link = NULL; node*cur = NULL; int ileftsize = ilength; while(NULL != p) { ileftsize--; if(i++ <= k) { node* tpm = (node*)malloc(sizeof(node)); tpm->data = p->data; tpm->next = p->next; if(NULL == tpm_link) { tpm_link = tpm; cur = tpm_link; } else { cur->next = tpm; cur = tpm; } if(i == k || ileftsize == 0) { cur->next = NULL; i = 0; node*tmp_sort = ReverseLinkNode(tpm_link); tpm_link = NULL; if(NULL == new_link) { new_link = tmp_sort; } else //连接合并两个排序好的段 { node* j = new_link; while(1) { if(NULL == j->next) { j->next = tmp_sort; break; } j = j->next; } } } } p = p->next; } while(NULL != new_link) { cout << new_link->data << endl; new_link = new_link->next; } }