链表问题
输入一列整数,以0结束,把这些整数(不含0)顺序存放一单链表中,再把链表按照输入相反顺序处理并输出。请问上面这道题该怎么写? 本帖最后由 jackz007 于 2021-1-4 22:35 编辑
#include <stdio.h>
#include <stdlib.h>
struct node {
int d ;
struct node * next ;
} ;
// 反序链表所有节点
struct node *reverse(struct node * head)
{
struct node * h , * p , * q , * r ;
for(h = NULL , p = head ; p ; r = p , p = q) {
q = p -> next ;
if(p == head) p -> next = NULL ;
else p -> next = r ;
if(! q) h = p ;
}
return h ;
}
// 释放链表所有节点占用的内存
void release(struct node * head)
{
struct node * p , * q ;
for(p = head ; p ; p = q) {
q = p -> next ;
free(p) ;
}
}
int main(void)
{
struct node * h , * p , * q ;
int d , f , i , n ;
for(f = 1 , h = p = q = NULL ; f ; q = p) {
scanf("%d" , & d) ;
if(d) {
if((p = (struct node *)malloc(sizeof(struct node)))) {
p -> d = d ;
p -> next = NULL ;
if(h) q -> next = p ;
else h = p ;
} else {
fprintf(stderr , "\n") ;
fprintf(stderr , "*** error in alocate memory .\n") ;
fprintf(stderr , "\n") ;
f = 0 ;
break ;
}
} else break ;
}
if(h && f) {
printf("%d" , h -> d) ;
for(p = h -> next ; p ; p = p -> next) printf(" %d" , p -> d) ;
printf("\n") ;
h = reverse(h) ;
printf("after reverse .\n") ;
printf("%d" , h -> d) ;
for(p = h -> next ; p ; p = p -> next) printf(" %d" , p -> d) ;
printf("\n") ;
release(h) ;
}
}
编译、运行实况
D:\00.Excise\C>g++ -o x x.c
D:\00.Excise\C>x
1 2 3 4 5 6 7 8 9 0
1 2 3 4 5 6 7 8 9
after reverse .
9 8 7 6 5 4 3 2 1
D:\00.Excise\C> jackz007 发表于 2021-1-4 22:32
编译、运行实况
谢谢!虽然暂时还看不懂,只是先应付下作业
页:
[1]