首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

看看这段小程序,关于链表存储的解决思路

2012-02-28 
看看这段小程序,关于链表存储的# include stdio.h# include malloc.htypedef struct Lnode{//定义结点

看看这段小程序,关于链表存储的
# include <stdio.h>
# include "malloc.h"
typedef struct Lnode{//定义结点
int data;
struct Lnode *next;
}Lnode,*Linklist;  
void Initlist(Linklist head){ //建立头结点
head=(Linklist)malloc(sizeof(Lnode));//申请空间
if(!head) return ;
head->next=0;
head->data=NULL;
}
Insertlist(Linklist head,int i,int elem){//插入元素
Lnode *p,*q;
p=head;
int pos;
q=(Linklist)malloc(sizeof(Lnode));//申请空间
if(!q) return 0;
q->data=elem;
for(pos=0;pos<i-1;pos++) //寻找插入的位置
p=p->next;
q->next=p->next;
p->next=q;
return 1;
}
void Printlist( Linklist head)//输出结果
{
Lnode *p;
p=head->next;
while(p->next!=NULL){
printf("%3d",p->data);
p=p->next;
}
printf("%3d",p->data);
}
void free(Linklist head){//释放空间
free(head);
}

void main()
{
Lnode *head=NULL;
Initlist(head);
int i;
for(i=1;i<10;i++)
Insertlist(head,i,i*i);//插入元素
Printlist(head);//输出元素
free(head);
}
为什么这样写不正确啊

[解决办法]
# include <stdio.h>
# include "malloc.h"
typedef struct Lnode{//定义结点
int data;
struct Lnode *next;
}Lnode,*Linklist;
void Initlist(Lnode **head){//建立头结点 //这个位置应该用二级指针,才能改变你传进来的参数
*head=(Linklist)malloc(sizeof(Lnode));//申请空间
if(!*head) return ;
(*head)->next = NULL;//不标准,应改为 head->next = NULL; 
(*head)->data = 0;// head->data = 0;
}
//是不是想新插入的结点做为首结点,可以改一下

int Insertlist(Lnode **head,int i,int elem){// 

Lnode *pNew = (Linklist)malloc(sizeof(Lnode));
if(NULL == pNew)
{
return 0;
}
pNew->next = *head;
*head = pNew;
pNew->data = elem;
return 1;
/*Lnode *p,*q;
p=head;
int pos;
q=(Linklist)malloc(sizeof(Lnode));//申请空间
if(!q) return 0;
q->data=elem;
for(pos=0;pos<i-1;pos++) //寻找插入的位置
p=p->next;
q->next=p->next;
p->next=q;
return 1;*/
}


void Printlist( Linklist head)//输出结果
{
/*Lnode *p;
p=head->next;
while(p->next!=NULL){
printf("%3d",p->data);
p=p->next;
}
printf("%3d",p->data);
*/
Linklist current = head;
while(current != NULL)
{
printf("%5d", current->data);
current = current->next;
}
}
//再来一个内存释放的函数
void FreeLinkedList(Linklist *head)
{
Linklist current = NULL;
while(*head != NULL)
{
current = *head;
*head = (*head)->next;
free(current);
}
}

热点排行