建立一个链表

2025-03-03 18:08:06
推荐回答(1个)
回答1:

//c语言实现链表的建立,按逆序复制
#include
#include
struct node
{
int info;//节点信息
struct node *next;
};
struct node *Create(int *numnode)
{//创建一个链表
struct node *head,*tail,*cnew;
head=NULL;
int num;
printf("输入数据(以零结束):");
while(1)
{
scanf("%d",&num);
if(num==0)//输入为零表示输入结束
break;
cnew=(struct node*)malloc(sizeof(struct node));
cnew->info=num;
cnew->next=NULL;
if(head==NULL)//若为空则将头节点指向新节点
head=cnew;
else
tail->next=cnew;//将当前节点的next指向新的节点
tail=cnew;
(*numnode)++;
}
return head;
}
struct node *ReverseCopy(struct node *head1,int *numnode)
{//复制链表函数反向复制
struct node *p,*head,*q;
head=NULL;//初始化为空
for(q=head1;q!=NULL;q=q->next)
{//根据head1链表来建立新的链表
p=(struct node *)malloc(sizeof(struct node));
p->info=q->info;//将head1链表的数据元素复制到新的节点中
p->next=head;//将新节点的的next指向头节点
head=p;
//将head移向新的节点,for语句结束head就指向了最后建立的节点处即head1的最后一个节点处
//每次插入都是在head和新节点之间移动
(*numnode)++;
}
return head;
}
void show(struct node *head)
{//遍历链表输出
struct node *p;
if(head==NULL)
{
printf("链表为空,没有数据\n");
return;
}
printf("\n-----链表的数据元素------\n");
for(p=head;p!=NULL;p=p->next)
printf("%d ",p->info);
printf("\n");
}
int main()
{
struct node *head1,*head2;
int numnode1,numnode2;
numnode1=numnode2=0;
head1=head2=NULL;
//初始化将节点个数初始化为零
head1=Create(&numnode1);
show(head1);
printf("\n链表head1的节点个数为:%d\n",numnode1);
head2=ReverseCopy(head1,&numnode2);
//调用复制函数,完成复制
show(head2);
printf("\n链表head2的节点个数为:%d\n",numnode2);
return 0;
}