分享一个链表的程序,交流心得[非求助帖]
程序代码:#include<stdio.h>
#include<stdlib.h>
#define INFEASIBLE -2;
#define OK 0;
struct node{
int data;
struct node *next;
};
typedef struct node linklist;
int creast(linklist *h,int n);//定义创建链表的函数
int del(linklist *h);//定义删除链表第一个数的函数
int scan(linklist *h);//定义查看整个链表的函数
int mp(linklist *h);//定义冒泡函数
int main(){
int n,i;
linklist *h;
printf("Please input the n:");
scanf("%d",&n);//输入要创建的链表的元素个数
h=(linklist*)malloc(sizeof(struct node));//给头节点申请空间
creast(h,n);//创建
mp(h);//冒泡排序
for(i=0;i<n;i++){
scan(h);//输出
del(h);//删除第一个数
printf("\n");
}
return 0;
}
int creast(linklist *h,int n){//头插法建立链表
printf("Please input the data:");
int i;
linklist *p;
if(!h)
return INFEASIBLE;
h->next=NULL;
for(i=n;i>0;i--){
p=(linklist*)malloc(sizeof(struct node));
if(!p)
return INFEASIBLE;
scanf("%d",&p->data);
p->next=h->next;
h->next=p;
}
return OK;
}
int scan(linklist *h){
linklist *m;
if(h==NULL) printf("Empty List!\n");
m=(linklist*)malloc(sizeof(struct node));
m=h->next;
while(m){
printf("%d\t",m->data);
m=m->next;
}
return OK;
}
int del(linklist *h){
linklist *q;
q=(linklist*)malloc(sizeof(struct node));
q=h->next;
h->next=q->next;
free(q);
return OK;
}
int mp(linklist *h){
linklist *e,*f;//创建中间的变量
int a;
if(h==NULL) return INFEASIBLE;//头节点不空
for(e=h->next;e!= NULL;e=e->next){//控制总体排列次数
for(f=h->next;f->next!=NULL;f=f->next){//控制每一大次排列次数
if(f->data > f->next->data){
a=f->data;
f->data = f->next->data;
f->next->data=a;
}
}
}
free(e);
//free(f);
return OK;
}另外想问,为啥有free(f)就会把指针搞乱,导致最后一位乱码,没有就能正常运行。。。。

