C言語にてリスト構造をつくり、1行の入力文字列をリスト化するというプログラムを作りました。
そのうち、入力の文字列をN個として、リストの先頭からN/2番目までの要素と、N/2+1番目から末尾までの要素を交換すると言う関数halfchangeを作ったのですが、うまく機能しません。
わかる方、教えてください。
また、実現したい実行例は以下のとおりです。
$./a.out tokyo kyoto $./a.out yuyakekoyake koyakeyuyake
実際に実行すると以下のようになります
$ ./a.out tokyo to ./a.out yuyakekoyake yuyake
C
1#include <stdio.h> 2#include <stdlib.h> 3 4struct node{ 5 char element; 6 struct node *next; 7}; 8 9struct node *initlist() { 10 struct node *n; 11 n=(struct node *)malloc(sizeof(struct node)); 12 n->next=NULL; 13 return n; 14} 15 16void insert(struct node *p, char x) { 17 struct node *n; 18 n=(struct node *)malloc(sizeof(struct node)); 19 while(p->next){ 20 p=p->next; 21 } 22 n->element=x; 23 n->next = NULL; 24 p->next=n; 25} 26 27void printlist(struct node *p) { 28 p = p->next; 29 while (p) { 30 putchar(p->element); 31 p = p->next; 32 } 33 putchar('\n'); 34} 35 36void halfchange(struct node *p) { 37 int i=0; 38 struct node *tmp=p; 39 struct node *start=p; 40 while(p->next!=NULL){ 41 i++; 42 p=p->next; 43 } 44 struct node *endp=p; 45 i=i/2; 46 47 while(i>=1){ 48 i--; 49 tmp=tmp->next; 50 } 51 struct node *half=tmp->next;//half 52 struct node *half_pre=tmp;//half-1 53 endp->next=start->next; 54 //printlist(endp); 55 half_pre->next=NULL; 56 //printlist(half); 57 p->next=half->next; 58} 59 60int main(int argc, char *argv[]) { 61 struct node *list, *head; 62 char *p; 63 64 if (argc<2) 65 exit(-1); 66 67 list = initlist(); 68 p = argv[1]; 69 for (; *p; p++) { 70 insert(list, *p); 71 } 72 73 halfchange(list); 74 printlist(list); 75 76 for (; list; ) { 77 head = list; 78 list = list->next; 79 free(head); 80 } 81 return 0; 82} 83 84 85
回答2件
あなたの回答
tips
プレビュー