#include <iostream>
using namespace std;
typedef struct Node
{
int count;
struct Node *next;
}node;
node* mycreat(int n)
{
int val;
node *head=NULL,*p=NULL,*ne=NULL;
head=(node*)malloc(sizeof(node));
p=head;//存好头指针
while(n--)
{
scanf("%d",&val);
ne=(node*)malloc(sizeof(node));//开辟写一个指针的空间
ne->count=val; //下一个指针存的值是刚输进的值
p->next=ne; //将这个指针与下一个链接起来
p=ne;//将动态指针指向下一个
}
p->next=NULL;//p更新到这里指的是最后一个链,此时他的next不存在值定为null
return head;//返回头指针
}
void myprint(node *head)
{
int f=0;
node *p=NULL;
p=head->next;//指针指向头指针的下一个
while(p!=NULL)//只要p不为空
{
if(f==0)
printf("%d",p->count);//输出动态p此时指向链的数值
else
printf(" %d",p->count);
f++;
p=p->next;//动态p指向下一个链
}
printf("\n");
return;
}
int main()
{
int n;
node *head;
while(~scanf("%d",&n))
{
head=mycreat(n);
myprint(head);
}
return 0;
}
单链表的建立和遍历
最新推荐文章于 2023-01-07 18:29:36 发布