返回   cpper编程论坛 > 技术杂烩
注册账号 论坛帮助 会员列表 日历事件 搜索 今日新帖 标记版面已读

技术杂烩 找不到地方的技术问题?这里!

回复
 
LinkBack 主题工具 显示模式
  #1 (permalink)  
旧 2002-10-06
初级会员
 
注册日期: 2002-09-13
帖子: 29
uniqlo1 正向着好的方向发展
默认 一所较有名大学的数据结构教材中的例<关于List>

代码:
#include<stdio.h> #include<stdlib.h> struct cell { int element; struct cell *next; }; //函数的宣言 ... main() .... /*将x代入p指向的cell的下一个cell,list从init开始*/ struct cell *insert(int x, struct cell *p,struct cell *init) { struct cell *q,*r; r=(struct cell *)malloc(sizeof(struct cell)); if(p==NULL) { q=init; init=r; } else { q=p->next; p->next=r; } r->element=x; r->next=q; return (init); } /*在从init开始的list中,将p指向的cell的下一个cell删除*/ struct cell *delete(struct cell *p,struct cell *init) { struct cell *q; if(init==NULL) { printf("Error: List is empty.\n"); exit(1); } if(p==NULL) { q=init; init=init->next; free(q); } else { if(p->next==NULL) { printf("Error: No element to remove.\n"); exit(1); } else { q=p->next; p->next=q->next; free(q); } } return init; }
请各位高手高手高高手帮我看看有否问题。
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
回复时引用此帖
  #2 (permalink)  
旧 2002-10-06
高级会员
 
注册日期: 2002-09-10
帖子: 269
文章: 1
panda 正向着好的方向发展
发送 MSN 消息给 panda
默认

既然是教材,我想应该没问题!但是风格很不好,显然是用c写的,和我们公司PS时期的代码长得倒很象!估计pora看到肯定要说:看STL的源码去!
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
回复时引用此帖
  #3 (permalink)  
旧 2002-10-07
abp 的头像
abp abp 当前离线
高级会员
 
注册日期: 2002-08-30
帖子: 811
abp 正向着好的方向发展
默认

说实话,我觉得这些函数的参数传递方式有问题
可能链表有个头会好一些。
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
回复时引用此帖
  #4 (permalink)  
旧 2002-10-09
初级会员
 
注册日期: 2002-09-13
帖子: 29
uniqlo1 正向着好的方向发展
默认

我记得malloc 与free 是配套使用的呀,可是在delete()函数中,他也没有去

用malloc去确保q,却在后面用free去释放q,这样也可以吗?

而对于insert函数中同样的临时变数q,他却既不malloc也不free也可以吗?

Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
回复时引用此帖
  #5 (permalink)  
旧 2002-10-09
polyrandom 的头像
超级版主
 
注册日期: 2002-09-03
帖子: 3,138
文章: 20
polyrandom 正向着好的方向发展
默认

没什么问题。malloc和free的确是要相对的,但是不必要在同一个函数里面。只要能够保证malloc分配的内存被free释放就行了。
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
回复时引用此帖
  #6 (permalink)  
旧 2002-10-14
初级会员
 
注册日期: 2002-09-13
帖子: 29
uniqlo1 正向着好的方向发展
默认

懂了。 :P
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
回复时引用此帖
回复

书签

主题工具
显示模式

发帖规则
不可以发表新主题
不可以发表回复
不可以上传附件
不可以编辑自己的帖子

启用 BB 代码
论坛启用 表情符号
论坛启用 [IMG] 代码
论坛禁用 HTML 代码
Trackbacks are 启用
Pingbacks are 启用
Refbacks are 启用



所有时间均为格林尼治时间 +9。现在的时间是 06:28 AM


Powered by vBulletin® 版本 3.7.0
版权所有 ©2000 - 2009,Jelsoft Enterprises Ltd.
(C) Copy Right All Right Reserved 2001 - 2007

Search Engine Friendly URLs by vBSEO 3.1.0