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;
}
}
添加回答
舉報