#include
#include
typedef struct node{
int data;
struct node *next;
}*sqlist;//定义链表结构
sqlist creatlist(int n){//创建单向链表
sqlist head,p,q;
head=p=(sqlist)malloc(sizeof(node));
for(int i=0;i q=(sqlist)malloc(sizeof(node));
q->data=i;
p->next=q;
p=q;
}
p->next=NULL;
return head;
}
void printlist(sqlist head){// 创建单向非循环链表
sqlist p=head->next;
while(p!=NULL){
printf("%d",p->data);
p=p->next;}
printf("\n");
}
void freelist(sqlist head){//释放链表
sqlist p,q;
p=head;
q=p->next;
while(q!=NULL){
q=p;
q=q->next;
free(p);}
free(head);
}
int main(){
int n;
sqlist head;
scanf("%d",&n);
head=creatlist(5);
printlist(head);
freelist(head);
return 0;
}
创建单项链表for循环有问题
修改了下
sqlist creatlist(int n)//尾插法创建有头结点的单向链表
{
sqlist head, p, q;
head = (sqlist)malloc(sizeof(struct node));
p = head;
for(int i = 0;i < n; i++)
{
q = (sqlist)malloc(sizeof(struct node));
q->data = i;
p->next = q;
p = q;
}
p->next=NULL;
return head;
}
还有就是释放内存那
void freelist(sqlist head)
{//释放链表
sqlist p,q;
p = head;
while(q!=NULL)
{
p = q;
q = p->next;
free(p);
}
}