第一步先建立一个链表并输出。
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
};
int main()
{
int a,n,m,i,j,k;
struct node *head,*p,*q,*t;
scanf("%d",&n);
head=NULL;
for(i=1;i<=n;i++)
{
scanf("%d",&a);
p=(struct node *)malloc(sizeof(struct node));
p->data=a;
p->next=NULL;
if(head==NULL)
{
head=p;
}
else if(head!=NULL)
{
q->next=p;
}
q=p;
}
t=head;
while(t!=NULL)
{
printf("%d ",t->data);
t=t->next;
}
return 0;
}
第二步 插入一个元素
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
};
int main()
{
int a,n,m,i,j,k;
struct node *head,*p,*q,*t;
scanf("%d",&n);
head=NULL;
for(i=1;i<=n;i++)
{
scanf("%d",&a);
p=(struct node *)malloc(sizeof(struct node));
p->data=a;
p->next=NULL;
if(head==NULL)
{
head=p;
}
else if(head!=NULL)
{
q->next=p;
}
q=p;
}
t=head;
while(t!=NULL)
{
printf("%d ",t->data);
t=t->next;
}
printf("\n请输入需要插入的内容\n");
scanf("%d",&m);
t=head;
while(t!=NULL)
{
p=(struct node *)malloc(sizeof(struct node));
if(t->next==NULL||t->next->data>m)
{
p->data=m;
p->next=t->next;
t->next=p;
break;
}
t=t->next;
}
t=head;
while(t!=NULL)
{
printf("%d ",t->data);
t=t->next;
}
return 0;
}