給學生出的一道題,後來發現出得難了,乾脆自己做了一下,當是練練手吧。
#include <stdio.h><br />#include <stdlib.h><br />typedef struct _chain<br />{<br />int n;<br />struct _chain *next;<br />}chain;</p><p>void print_list(const chain * head)<br />{<br />chain * p;<br />p=head->next;<br />while(p){<br />printf("%d->", p->n);<br />p=p->next;<br />}<br />printf("END/n");<br />printf("共%d個。/n", head->n);<br />}</p><p>void free_list(const chain * head)<br />{<br />chain * p, *temp;<br />p=head->next;<br />while(p){<br />temp=p->next;<br />free(p);<br />p=temp;<br />}<br />}</p><p>void create_list_from_array(chain * head, int n[], int len)<br />{<br />int i;<br />chain * p=head;</p><p>for (i=0;i<len;i++){<br />p->next = (chain*)malloc(sizeof(chain));<br />p=p->next; /*!*/<br />p->n = n[i];<br />++head->n;<br />}<br />p->next=0;<br />}</p><p>chain* reverse_list(chain * to_be_next,<br /> chain ** tail)<br />{<br />chain * r;</p><p>if(to_be_next->next == 0){<br />*tail = to_be_next;<br />}<br />else{<br />r = reverse_list(to_be_next->next, tail);<br />r->next = to_be_next;<br />}<br />return to_be_next;<br />}</p><p>void do_reverse_list(chain *head)<br />{<br />chain *tail=0;<br />chain *tmp;</p><p>tmp = reverse_list(head->next, &tail);<br />tmp->next=0;<br />head->next = tail;<br />}</p><p>void main()<br />{<br />chain head;<br />chain *p;<br />int len;</p><p>int s[]={2,3,1,6,8,9,5,4,8,10};<br />len=sizeof(s)/sizeof(s[0]);<br />head.n=0;<br />p=&head;</p><p>create_list_from_array(&head, s, len);<br />print_list(&head);</p><p>do_reverse_list(&head);<br />print_list(&head);</p><p>//!<br />free_list(&head);<br />system("pause");<br />}<br />