|
发表于 2022-12-6 19:27:16
|
显示全部楼层
本帖最后由 jhq999 于 2022-12-6 19:37 编辑
- #include <stdio.h>
- struct cityLN {
- char name[20];
- int population;
- struct cityLN *next;
- };
- void printCities(struct cityLN *ct);
- struct cityLN * reverseCitiesRecursive(struct cityLN *ct, struct cityLN *dt);
- int main(){
- struct cityLN c1 = {"Hiratsuka", 258, NULL},
- c2 = {"Odawara", 190, NULL},
- c3 = {"Yokosuka", 396, NULL},
- c4 = {"Kamakura", 172, NULL},
- c5 = {"Chigasaki", 242, NULL},
- c6 = {"Fujisawa", 434, NULL};
- struct cityLN *head = NULL;
- head = &c1; c1.next = &c2; c2.next = &c3; c3.next = &c4; c4.next = &c5; c5.next = &c6;
- printf("Original: \n");
- printCities(head);
- printf("reverse: \n");
- struct cityLN * tmp=head;
- head = reverseCitiesRecursive(head, head->next);
- tmp->next=NULL;
- printCities(head);
- return 0;
- }
- void printCities(struct cityLN *ct){
- if (ct != NULL) {
- printf("(%-10s: population = %3d)", ct->name, ct->population);
- printf("%s", (ct->next != NULL) ? " ->\n" : "");
- printCities(ct->next);
- }
- else
- putchar('\n');
- }
- struct cityLN * reverseCitiesRecursive(struct cityLN *ct, struct cityLN *dt){
- if (dt->next == NULL) {
- dt->next=ct;
- return dt;
- }
- struct cityLN * tmp=dt->next;
- dt->next=ct;
- return reverseCitiesRecursive(dt,tmp);
- }
复制代码- struct cityLN * reverseCitiesRecursive(struct cityLN *head){
- struct cityLN *p=head->next,*tmp;
- head->next=NULL;
- while(p->next)
- {
- tmp=p->next;
- p->next=head;
- head=p;
- p=tmp;
- }
- p->next=head;
- return p;
- }
复制代码 |
|