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

C语言链表插入有关问题

2013-01-22 
C语言链表插入问题#includestdio.h#includestdlib.htypedef struct node{int numstruct node *next}

C语言链表插入问题

#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
int num;
struct node *next;
}Node,*NODE;
NODE create()
{
int n;
NODE h,t,s;
h=t=NULL;
while(scanf("%d",&n)==1)
{
s=(NODE)malloc(sizeof(Node));
s->num=n;
s->next=NULL;
if(h==NULL)
h=t=s;
else
t=t->next=s;}
return h;
}
void show(NODE head)
{
NODE q,s;
q=head;
while(q)
{
printf("%d\n",q->num);
s=q->next;
free(q);
q=s;
}
}
void insert(NODE head)
{
int n,m;
int c=0;
NODE h=head;
printf("please input insert num:\n");
getchar();
scanf("%d",&n);
printf("please decide where u insert:\n");
scanf("%d",&m);
while(h!=NULL)
{
if((c++)==m)
{
NODE s=(NODE)malloc(sizeof(Node));
s->num=n;
s->next=h->next;
h->next=s;
break;
}
h=h->next;
}
}
int main(void)
{
NODE head;
head=create();
show(head);
insert(head);
show(head);
return 0;
}
为什么不能正常插入?
[解决办法]
#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
    int num;
    struct node *next;
} Node,*NODE;
NODE create()
{
    int n;
    NODE h,t,s;
    h=t=NULL;
    while(scanf("%d",&n)==1)
    {
        s=(NODE)malloc(sizeof(Node));
        s->num=n;
        s->next=NULL;
        if(h==NULL)
            h=t=s;
        else
            t=t->next=s;
    }
    return h;
}
void show(NODE head)
{
    NODE q,s;
    q=head;
    while(q)
    {
        printf("%d\n",q->num);
        s=q->next;
       // free(q);            //修改的地方
        q=s;
    }
}
void insert(NODE head)
{
    int n,m;
    int c=0;
    NODE h=head;
    printf("please input insert num:\n");
    getchar();
    scanf("%d",&n);
    printf("please decide where u insert:\n");
    scanf("%d",&m);
    while(h!=NULL)
    {
        if((c++)==m)
        {



            NODE s=(NODE)malloc(sizeof(Node));
            s->num=n;
            s->next=h->next;
            h->next=s;
            break;
        }
        h=h->next;
    }
}
int main(void)
{
    NODE head;
    head=create();
    show(head);
    insert(head);
    show(head);
    return 0;
}

 由于你把链表的每个节点的内存都释放了,导致链表不再包含原来的数值,节点变为地址,释放节点应该用于删除节点,在其他函数中,如果没有创建节点,就不要随便删除节点
[解决办法]
void show(NODE head)
{
NODE q,s;
q=head;
while(q)
{
printf("%d\n",q->num);
s=q->next;
free(q); //出掉
q=s;
}
}

热点排行