Files
python/C++课程/待整理知识/啊哈算法/p47.cpp
HuangHai 1f397eca87 'commit'
2025-08-30 18:35:01 +08:00

40 lines
1023 B
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include<bits/stdc++.h>
//链表结构体,一个真实的数字,一个是指针,指向下一个node的地址
struct node {
int data;
struct node *next;
};
int main() {
struct node *head ,*p,*q,*t;//第一个指针
int i, n, a; //变量声明
scanf("%d",&n); //创建一个多大的链表
head = NULL; //头指针初始为空
//循环读入n个数
for(i = 1; i <= n; i++) {
scanf("%d",&a); //读入一个整数,放到a变量中
//动态申请一个空间,用来存放一个节点,并用临时指针p指向这个节点
p=(struct node *)malloc(sizeof(struct node));
p->data=a; //将数据存储到当前节点的data域中
p->next=NULL; //设置当前节点的后继指针指向空,也就是当前节点的下一个节点为空。因为是最后一个节点,所以next=NULL
//如果这是第一个创建的节点,则将上一个节点的后继指针指向当前节点
if(head==NULL)
head=p;
else
q->next=p; //如果不是第一个创建的节点,则将上一个节点的后继指针指向当前节点
//把本轮的变成上一个,方便下一轮循环
q=p;
}
//输出
t=head;
while(t!=NULL) {
printf("%d ",t->data);
t=t->next;
}
return 0;
}