C语言逆序输出

在这里插入图片描述
方法一:

#include<stdio.h>

int main(){
    
    
	int n;
	int i=0;
	int arr[5];
	while(1){
    
    
		scanf("%d", &n);
		if(n==-1){
    
    
			break;
		}
		arr[i]=n;
		i++;
	}
	int len=sizeof(arr)/sizeof(arr[0]);
	int x=0;
	for(x=i-1;x>=0;x--){
    
    
		printf("%d ", arr[x]);
	}
	
	return 0;
}

方法二:

#include <stdio.h>
#include <stdlib.h>
struct node {
    
    
    int cou;
    struct node *next;//指针域
};
 
int main(void)
{
    
    
    struct node * head = NULL;//头结点初始为空
    int num;
    do{
    
    
        scanf("%d", &num);
        if(num!=-1)
        {
    
    
            struct node *p=(struct node *)malloc(sizeof(struct node));
            p->cou = num;
            p->next = head;//p->next为头结点,将新节点p连接到链表上
            head = p;
        }
    }while(num!=-1);
    struct node *p;//遍历
    for ( p = head; p; p=p->next) {
    
    
        printf("%d ", p->cou);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_44337241/article/details/112570042