对链表进行排序

#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
struct node
{
int data;
struct node *pnext;
};
struct node *creat_list();//建立链表函数
void traverse_list(struct node *phead);//遍历链表函数
bool is_empty(struct node *phead);//判断链表是否为空函数 
int lenght_list(struct node *phead);//计算链表长度的函数 
void sort_list(struct node *phead);//对链表进行排序 
int insert_list(struct node *phead,int weizhi,int shu );//插入节点函数 
int delete_list(struct node *phead ,int weihzi);//删除节点函数 
int main()
{
struct node *phead;
    
phead=creat_list();
traverse_list(phead);
if(is_empty(phead))
printf("链表不为空!\n");
else
printf("链表为空!\n");
int len=lenght_list(phead);
printf("链表的节点个数为:%d\n",len);
printf("排序后的链表为:");
    sort_list(phead);
traverse_list(phead);
insert_list(phead, 3,6666);
traverse_list(phead);
delete_list(phead,3);
traverse_list(phead);
return 0;
}

struct node *creat_list()
{
struct node *phead,*ptail,*pnew;
phead=(struct node *)malloc(sizeof(struct node));
ptail=phead;
ptail->pnext=NULL;
if(NULL==phead)
{
printf("分配内存失败,终止程序!\n");
exit(0);
}
int len;//表示要建立的节点数
int val;
printf("请输入要建立的节点数:");
scanf("%d",&len); 
for(int i=0;i<len;i++)
{
printf("请输入%d个节点的数据:",i+1);
scanf("%d",&val);
pnew=(struct node *)malloc(sizeof(struct node));
if(NULL==pnew)
{
printf("分配内存失败,终止程序!\n");
exit(0);
}
pnew->data=val;
ptail->pnext=pnew;
pnew->pnext=NULL;
ptail=pnew;
return phead;
}

void traverse_list(struct node *phead)
{
struct node *p=phead->pnext;
while(p!=NULL)
{
printf("%d ",p->data);
p=p->pnext;
printf("\n");
return ;

bool is_empty(struct node *phead)
{
if(phead->pnext!=NULL)
return true;
else
return false;
}

int lenght_list(struct node *phead)
{
struct node *p=phead->pnext;
int len=0;
while(p!=NULL)
{
len++;
p=p->pnext;
}
return len;
}
void sort_list(struct node *phead)
{
int len=lenght_list(phead);//链表的长度 
int i,j;
struct node *p,*q;
if(len==0)
printf("链表为空,无需排序!\n");
for(i=0,p=phead->pnext;i<len-1;i++,p=p->pnext)
{
for(j=i+1,q=p->pnext;j<len;j++,q=q->pnext)
{
if(p->data>q->data)
{
int temp=p->data;
p->data=q->data;
q->data=temp;
}
}
}
return ;
int insert_list(struct node *phead,int weizhi,int shu )
{
int i=0;
struct node *p=phead;
while(NULL!=p && i<weizhi-1)//很好的算法 
{
p=p->pnext;
i++;
}
if(i>weizhi-1 || NULL==p)
return false;
struct node *pnew=(struct node *)malloc(sizeof(struct node));
if(NULL==pnew)
{
printf("内存分配失败!\n");
}
pnew->data=shu;
struct node *ptail=p->pnext;
p->pnext=pnew;
pnew->pnext=ptail;
//free(ptail); //为何不能够释放掉呢 
return true;
int delete_list(struct node *phead ,int weizhi)
{
int i=0;
struct node *p=phead;
while(NULL!=p->pnext && i<weizhi-1)//很好的算法 
{
p=p->pnext;
i++;
}
if(i>weizhi-1 || NULL==p)
return false;
struct node *ptail;//临时指针 
ptail=p->pnext;
p->pnext=ptail->pnext;
free(ptail);
return true;
相关文章
相关标签/搜索