2 回答

TA贡献1786条经验 获得超13个赞
#include<stdio.h>
#include<malloc.h>
typedef struct node
{
int data;
struct node *next;
}node;
node *head,*p1,*p2;
/*建链表*/
void creat()
{ int i;
head=p1=(node*)malloc(sizeof(node));
for(i=0;i<30;i+=2)
/*已知带头节点的单链表L中的结点是按整数值递增排列的(就赋0-28所有偶数了
)*/
{
p2=(node*)malloc(sizeof(node));
p2->data=i;
p1->next=p2;
p1=p2;
}
p1->next=NULL;
}
/*插入结点*/
void insert(node* temp)
{ p1=head->next;
p2=head;
while(p1!=NULL&&(temp->data)>(p1->data))
{
p2=p1;
p1=p2->next;
}
if(p1!=NULL)
{
temp->next=p1;
p2->next=temp;
}
else
{
p2->next=temp;
temp->next=NULL;
}
}
/*输出链表*/
void print()
{
p1=head->next;
while(p1!=NULL)
{
printf("%d->",p1->data);
p1=p1->next;
}
printf("\n");
}
/*主函数*/
int main()
{ node *temp;
creat();
printf("原链表为:\n");
print();
temp=(node*)malloc(sizeof(node));
printf("输入要插入的值\n");
scanf("%d",&temp->data);
insert(temp);
printf("插入结点后链表为:\n");
print();
return 0;
}
#include<stdio.h>
#include<malloc.h>
typedef struct node
{
int data;
struct node *next;
}node;
node *head,*p1,*p2;
/*建链表*/
void creat()
{ int i;
head=p1=(node*)malloc(sizeof(node));
for(i=0;i<30;i+=2)
/*已知带头节点的单链表L中的结点是按整数值递增排列的(就赋0-28所有偶数了
)*/
{
p2=(node*)malloc(sizeof(node));
p2->data=i;
p1->next=p2;
p1=p2;
}
p1->next=NULL;
}
/*插入结点*/
void insert(node* temp)
{ p1=head->next;
p2=head;
while(p1!=NULL&&(temp->data)>(p1->data))
{
p2=p1;
p1=p2->next;
}
if(p1!=NULL)
{
temp->next=p1;
p2->next=temp;
}
else
{
p2->next=temp;
temp->next=NULL;
}
}
/*输出链表*/
void print()
{
p1=head->next;
while(p1!=NULL)
{
printf("%d->",p1->data);
p1=p1->next;
}
printf("\n");
}
/*主函数*/
int main()
{ node *temp;
creat();
printf("原链表为:\n");
print();
temp=(node*)malloc(sizeof(node));
printf("输入要插入的值\n");
scanf("%d",&temp->data);
insert(temp);
printf("插入结点后链表为:\n");
print();
return 0;
}
单链表插入一个值后有序排列

TA贡献1844条经验 获得超8个赞
#include<stdio.h>
#include<malloc.h>
struct node{
int key;
struct node *next;
};
void creat_link(struct node *);
main()
{
struct node *head=NULL;
creat_link(head);
}
void creat_link(struct node *head_node)
{
struct node *p,*q,*Temp;
int number;
printf("Please input data:[-1 is End]\n");
scanf("%d",&number);
while(number!=-1){
q=(struct node *)malloc(sizeof(struct node));
q->key=number;
if(head_node==NULL ){
head_node=q;
p=q;
}
else{
p->next=q;
p=q;
}
scanf("%d",&number);
}
p->next=NULL;
Temp=head_node;
while(Temp!=NULL){
printf("%d\n",Temp->key);
Temp=Temp->next;
}
}
添加回答
举报