前言
本篇文章主要介绍如何用c语言实现创建一个有序链表,并插入节点后仍使链表有序。
一起来学习吧!
目录
一.定义一个结构体
#include "stdio.h"
#include "malloc.h"
struct student {
int data;
struct student *next;
};
data用于存放数据,next 是struct student 类型的指针,用来存放地址
二.主函数
main()
{
struct student *head;
struct student *p;
int data;
head=createList();//创建有序链表
printList(head);//打印输出链表
scanf("%d",&data);
p=(struct student *)malloc(sizeof(struct student));
//p指向新建节点
p->data=data;
insertList(head,p);//插入节点,使链表仍有序
printList(head);//打印插入节点后的链表
}
三.创建链表
struct student *createList(){
struct student *head;
struct student *q;
struct student *p;
int data;
head=(struct student *)malloc(sizeof(struct student));
head->next=NULL;
scanf("%d",&data);
while(data!=0){
p=(struct student *)malloc(sizeof(struct student));
p->data=data;
insertList(head,p);
scanf("%d",&data);
}
return head;
}
四.打印链表
void printList(struct student *head){
struct student *phead;
phead=head->next;
while(phead!=NULL){
printf("%4d",phead->data);
phead=phead->next;
}
printf("\n");
}
五.插入节点并使链表有序
void insertList(struct student *head,struct student *p){
struct student *q;
struct student *preq;
preq=head;
q=head->next;
//找到p,preq的位置
while((q!=NULL)&&(q->data<p->data)){
preq=preq->next;
q=q->next;
}
//标准插入,把p插入到preq之后
p->next=preq->next;
preq->next=p;
}
六.总代码
#include "stdio.h"
#include "malloc.h"
//定义一个结构体
struct student {
int data;//放数据
struct student *next;//放地址
};
struct student *createList();
void printList(struct student *head);
void insertList(struct student *head,struct student *p);
main()
{
struct student *head;
struct student *p;
int data;
head=createList();
printList(head);
scanf("%d",&data);
p=(struct student *)malloc(sizeof(struct student));
p->data=data;
insertList(head,p);
printList(head);
}
struct student *createList(){
//创建有序链表
struct student *head;
struct student *q;
struct student *p;
int data;
head=(struct student *)malloc(sizeof(struct student));
head->next=NULL;
scanf("%d",&data);
while(data!=0){
p=(struct student *)malloc(sizeof(struct student));
p->data=data;
insertList(head,p);
scanf("%d",&data);
}
return head;
}
void printList(struct student *head){
//打印链表
struct student *phead;
phead=head->next;
while(phead!=NULL){
printf("%4d",phead->data);
phead=phead->next;
}
printf("\n");
}
void insertList(struct student *head,struct student *p){
//插入节点,使链表仍有序
struct student *q;
struct student *preq;
preq=head;
q=head->next;
while((q!=NULL)&&(q->data<p->data)){
preq=preq->next;
q=q->next;
}
p->next=preq->next;
preq->next=p;
}
七.运行结果
1 7 4 0
1 4 7
3
1 3 4 7
--------------------------------
Process exited after 9.281 seconds with return value 10
请按任意键继续. . .