C language "Dynamic Memory Allocation"

First input a positive integer n, then input any n integers, and then output these n integers in reverse order. The dynamic memory allocation method is required to allocate space for these n integers.
Input
contains two lines, the
first line, an integer n (0<n<=1000), the
second line, n integers

Output
the result of n integers in reverse order
Sample Input
3
1 2 3
Sample Output
3 2 1

#include<stdio.h>
#include<malloc.h>
#define zheng int
typedef struct LNode{
    
    
	zheng data;
	struct LNode *next;
}LNode,*Linklist;
//定义一个结构体重命名为LNode,*Linklist
int main()
{
    
    
	Linklist l,p;//创建第一个线性表 
	l=(LNode*)malloc(sizeof(LNode));//对他分配空间 
	l->next =NULL;//最后一个线性表指向null
	p=l;
	int n,t;
	scanf("%d",&n); //输入n个数 
	while(n--)//创建n个链表 
	{
    
    
		Linklist s;//创建链表作为中介 
		s=(LNode*)malloc(sizeof(LNode));//给s分配空间 
		scanf("%d",&t);
		s->data=t;//把t的值给s这个结构的数据 指针用-> 整型用. 
		s->next=l->next;//第二个表代替l指向NULL,后一个表指向前一个表 
		l->next=s;//让l表一直指向新表,此时可以把l到最后一个表按逆序连起来 
		//p->next=s;//新建一个链表p,当两个链表相同时作用也相同,让p的下一个为新表 
		//p=s; //让p成为新表,把从l开始的表按顺序连起来 
	}
	//p->next=NULL;//让最后一个表p指向null 
	//此时空表l还在,让空表l指向下一个即可 
	l=l->next;
	while(l)//while null时会停止运行,可以从第一个开始到最后一个结构体进行操作 
	{
    
    
		printf("%d ",l->data);
		l=l->next;
	}//此时l已经被覆盖,链表已经损坏,只能当做一次性使用
	//想要多次使用,就要把表头赋值给别的表,让别的表当做一次性使用 
} 

Guess you like

Origin blog.csdn.net/ziyue13/article/details/109892581