對鏈表進行排序

#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;
相關文章
相關標籤/搜索