#include <stdio.h>
#include <stdlib.h>
struct student{
int num ;
struct student * next ;
} ;
int n ;
void print(struct student * head)
{
printf("\n") ;
if(head) {
printf("%d" , head -> num ) ;
head = head -> next ;
for(; head ; head = head -> next) printf("\t%d" , head -> num ) ;
printf("\n") ;
}
}
struct student * create()
{
struct student * head , * p1 , * p2 ;
int num ;
printf("\n") ;
for(n = 0 , p1 = p2 = head = NULL ; ; p2 = p1) {
printf("请输入数字 : ") ;
scanf("%d",& num ) ;
if(num > 0) {
if((p1 = (struct student *) malloc(sizeof(struct student)))) {
p1 -> num = num ;
p1 -> next = NULL ;
if(head) p2 -> next = p1 ;
else head = p1 ;
n ++ ;
} else {
for(p1 = head ; p1 ; p1 = p2) {
p2 = p1 -> next ;
free(p1) ;
}
fprintf(stderr , "\n") ;
fprintf(stderr , "Error : malloc()\n") ;
fprintf(stderr , "\n") ;
break ;
}
} else {
break ;
}
}
return head ;
}
struct student * nizhi(struct student * head)
{
struct student * p1 , * p2 , * p3 ;
for(p1 = head , p2 = NULL ; p1 ; p1 = p3) {
p3 = p1 -> next ;
if(p1 == head) p1 -> next = NULL ;
else p1 -> next = p2 ;
if(! p3) head = p1 ;
p2 = p1 ;
}
return head ;
}
int main(void)
{
struct student * h = NULL , * p1 , * p2 ;
h = create() ;
print(h) ;
h = nizhi(h) ;
print(h) ;
for(p1 = h ; p1 ; p1 = p2) {
p2 = p1 -> next ;
free(p1) ;
}
}
编译、运行实况D:\00.Excise\C>g++ -o x x.c
D:\00.Excise\C>x
请输入数字 : 100
请输入数字 : 101
请输入数字 : 102
请输入数字 : 103
请输入数字 : 104
请输入数字 : 105
请输入数字 : 106
请输入数字 : 107
请输入数字 : 108
请输入数字 : 109
请输入数字 : 0
100 101 102 103 104 105 106 107 108 109
109 108 107 106 105 104 103 102 101 100
D:\00.Excise\C>
|