[求助] 用链表实现多个字符串翻转
想用字符串链表实现字符串的部分反转:例如,输入: I have a cat
输出: cat a have I
测试发现,各函数功能貌似都没问题(代码里有测试用的main())。 但在main()中输入并以空格分割字符串,插入链表时有问题,只有最后一个字符串cat能被插入,输出变成:
cat cat cat cat
希望高手能帮忙看下~
谢啦
程序代码:
#include <stdio.h> #include <stdlib.h> struct strings { char *word; struct strings *next; }; struct strings *head; struct strings *insertWords(struct strings *head, char *input) { struct strings *currPtr, *newPtr; newPtr = (struct strings*)malloc(sizeof(struct strings)); if (newPtr != NULL) { currPtr = head; newPtr->word = input; newPtr->next = NULL; if (currPtr == NULL) { head = newPtr; currPtr = head; printf("done!\n"); return head; } while(currPtr->next != NULL) { currPtr = currPtr->next; } currPtr->next = newPtr; } else { printf("No enough memory!\n"); } //printf("done!\n"); return head; } struct strings* stringReverse(struct strings *head) { struct strings *p, *q, *r; if(head == NULL) { return NULL; } p = head; q = head->next; p->next = NULL; while(q != NULL) { r = q->next; q->next = p; p = q; q = r; } head = p; return head; } void stringDisp(struct strings *head) { struct strings *p1; p1 = head; while (p1 != NULL) { printf("%s", p1->word); printf(" "); p1 = p1->next; } printf("\n"); } main() { int i; char *strings_input = "I have a cat", *strings; char temp[100] ; head = NULL; if(strings_input == NULL) { printf("String is empty!\n"); exit(0); } while (*strings_input != '\0') { for(i = 0; *strings_input != ' '&& *strings_input != '\0'; strings_input++,i++) { temp[i]=*strings_input; } temp[i] = '\0'; strings = temp; if(*strings_input != '\0') strings_input++; //printf("temp = %s\n",temp); head = insertWords(head, strings); //stringDisp(head); } stringDisp(head); system("pause"); } /*main() { char *test1 = "first", *test2 = "second", *test3 = "third"; head = NULL; head = insertWords(head,test1); head = insertWords(head,test2); head = insertWords(head,test3); stringDisp(head); head = stringReverse(head); stringDisp(head); system("pause"); } */