链表按序插入节点

[size=medium]在一个有序的链表上插入一个节点,使得插入节点后的链表仍然有序[/size]


#include<stdio.h>
#define N 5
struct Node
{
int data;
struct Node *next;
};

//创建链表并初始化数据
struct Node *create()
{
int i;
struct Node *head,*p1,*p2;
head = p1 = p2 = (struct Node*)malloc(sizeof(struct Node));
head->data = 89101;
for(i=1; i<N; i++)
{
p1 = (struct Node*)malloc(sizeof(struct Node));
p1->data = 89102+2*i-1;
p2->next = p1;
p2 = p1;
}
p2->next = NULL;
return head;
}

//插入一个节点
void insert(struct Node *head, struct Node *p)
{
struct Node *pt = head;
int temp;
while(pt != NULL)
{
if(p->data < pt->data)
{
break;
}
pt = pt->next;
}
//将找到的大于p中的数据值的节点和p的数据进行交换
temp = pt->data;
pt->data = p->data;
p->data = temp;
//现在pt存储的是p的数据,p存储的是pt的数据,构造连接pt->p->
p->next = pt->next;
pt->next = p;
}

void main()
{
int i;
struct Node *head,*pt;
//创建一个链表
head = pt = create();
//创建一个新节点
struct Node *p;
p = (struct Node*)malloc(sizeof(struct Node));
p->data = 89102;
printf("链表初始数据:\n");
while(pt)
{
printf("%d\n", pt->data);
pt = pt->next;
}

printf("\n插入节点%d:\n", p->data);
//插入链表
insert(head, p);

pt = head;
while(pt)
{
printf("%d\n", pt->data);
pt = pt->next;
}


//插入一个节点
p = (struct Node*)malloc(sizeof(struct Node));
p->data = 89106;

printf("\n插入节点%d:\n", p->data);
insert(head, p);

pt = head;
while(pt)
{
printf("%d\n", pt->data);
pt = pt->next;
}

//插入一个节点
p = (struct Node*)malloc(sizeof(struct Node));
p->data = 89107;

printf("\n插入节点%d:\n", p->data);
insert(head, p);


pt = head;
while(pt)
{
printf("%d\n", pt->data);
pt = pt->next;
}
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值