免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1553 | 回复: 4
打印 上一主题 下一主题

为什么链表内不能插入节点 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2010-02-03 20:08 |只看该作者 |倒序浏览
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct all_sch_list
{
        char name[10];
        char scale[10];
        struct all_sch_list *next;
}all_sch_list_t, *sch_list_t;
                                                                                                                             
static sch_list_t sch_list = NULL;
int n = 0;
sch_list_t list_add(char *name, char *scale)
{
   sch_list_t new_node,prev,current;
                        
   new_node = (sch_list_t)malloc(sizeof(all_sch_list_t));
   strcpy(new_node->name, name);
   strcpy(new_node->scale, scale);
   new_node->next = NULL;

   n++;
   printf("%s n:%d\n", __FUNCTION__, n);         

   if(sch_list == NULL)
   {
        printf("000000\n");
           sch_list = new_node;
        sch_list->next = NULL;
   }
   else
   {
        printf("1111111\n");
        current = sch_list;
        while(current)
        {
            prev = current;
            current = current->next;
        }
        prev->next = new_node;
   }
   while(sch_list != NULL)
   {
       printf("sch list name:%s scale:%s\n", sch_list->name, sch_list->scale);
       sch_list = sch_list->next;
   }

   return sch_list;
}

static void print_list()
{
   while(sch_list != NULL)
   {
        printf("name:%s scale:%s\n", sch_list->name, sch_list->scale);
        sch_list = sch_list->next;
   }
}

void main()
{
   char name[10] = "name1";
   char scale[10] = "Good";
   list_add(name, scale);
   char name2[10] = "name2";
   char scale2[10] = "Very well";
   list_add(name2, scale2);
   print_list();
}

运行后结果:
list_add n:1
000000
sch list name:name1 scale:Good
list_add n:2
000000
sch list name:name1 scale:Very well

为什么每次list_add()后sch_list内容仍是空啊?

论坛徽章:
0
2 [报告]
发表于 2010-02-03 20:22 |只看该作者
根本没有往链表里添加数据的操作

论坛徽章:
0
3 [报告]
发表于 2010-02-04 09:07 |只看该作者
程序中判断链表是否为空,如果为空,sch_list = new_node,而new_node根据传入的参数作了处理,怎么说没有添加数据呢?

论坛徽章:
0
4 [报告]
发表于 2010-02-04 09:25 |只看该作者
sch_list = sch_list->next;

论坛徽章:
0
5 [报告]
发表于 2010-02-04 09:38 |只看该作者
明白了。谢谢。本来list_add()最后那个while循环是想看看调试信息的,结果反而把链表始终置空了。
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP