输入20个整数存放到一个单向链表中,并顺序逆序输出

时间:2022-12-12 11:02:34
#include<stdio.h>
#include<stdlib.h>
typedef struct node{
    int data;
    struct node *next;
}N;

N *head = (N *)malloc(sizeof(N));//创建头结点

void main(){
    N *r = head;//尾指针,开始指向头结点
    N *newPoint;
    printf("请输入任意个数据(用回车结束输入,空格间隔:1 2 3……)\n");
    do{
        newPoint = (N *)malloc(sizeof(N));//创建一个新节点
        scanf("%d", &newPoint->data);
        r->next = newPoint;
        r = newPoint;
    } while (getchar() != '\n');
    r->next = NULL;

    int a[100];
    int i = 0;
    N *cp = head->next;
    printf("顺序为:\n");
    while (cp){
        printf("%d\t", cp->data);
        a[i] = cp->data;
        i++;
        cp = cp->next;
    }
    printf("\n");
    printf("逆序为:\n");
    for (int j = i - 1; j >= 0; j--){
        printf("%d\t", a[j]);
    }
    printf("\n");
}