
正文
c语言链表结构体主函数 c语言链表和结构体
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
c语言结构体(链表)操作函数
if中可以赋值给head的理由很简单。
因为 if(PTScount(head) == 0)
if判断的就是看它是不是 第一个元素。
如果是第一个元素,自然直接将ins赋值给head。
head所代表的就是第一个元素。
如果到了else这里,那么很明显就不是第一个元素了。
那这个时候肯定就不可以直接复制给head了呀,因为head可是代表第一个元素呀。
所以,你这是肯定改不了的。
相关问答
Q1: C语言链表 主函数
1、添加头文件"stdio.h"
2、struct student * creat(void),但是你的main函数中返回接收却是用的int*类型。
3、主函数main应当明确声明为void main()
4、最为严重的是:struct student * creat(void) 函数体中使用了局部变量struct student *head; struct student *p1,*p2; 但是函数结束的地方却要返回这些指针,因此返回的值是无效数据。返回时,已经不再作用域了,是无效的空间。建议把这些数据当作输入参数,指针类型的。就可以正确的接收分配的struct student空间以及指针了。
5、struct student * creat(void) 函数体中,临时指针*p1、*p2再函数返回之前应当设置为NULL,避免因为局部变量的作用域结束导致相关的空间被清除。
总之,我建议把struct student * creat(void)定义修改为:
void creat(struct student **head).
以上内容经过调试,可以使用。
==================我的程序,经过完整的调试
#include "stdafx.h"
#include "malloc.h"
#include "stdio.h"
#define NULL 0
#define LEN sizeof(struct student)
struct student
{
long num;
float score;
struct student *next;
};
int n;
void creat(struct student **head) /*定义函数,此函数带回一个指向链表头的指针*/
{
struct student *p1,*p2;
n=0;
do
{
p1=(struct student *)malloc(LEN); /*开辟一个新单元*/
p1-next=NULL;
scanf("%ld,%f",p1-num,p1-score);
if(p1-num==0)
break;
n++;
if(n==1)
*head=p1;
else
p2-next=p1;
p2=p1;
} while(p1-num!=0) ;
p1=NULL;
p2=NULL;
}
void main()
{
struct student *p;
creat(p);
if(p!=NULL)
do
{
printf("%ld %5.1f\n",p-num,p-score);
p=p-next;
}while(p!=NULL);
flushall(); //清除键盘缓冲区,避免输入混淆
getchar(); //等待键盘任意输入,以便观察运算结果
}
看我的回答怎么样?
Q2: C语言链表的建立,输出,长度,元素的查找,删除,插入,主函数不知道怎么写!!!要可以编译的!!!谢谢
c语言链表结构体主函数你照下面这个 去写c语言链表结构体主函数:下面这个是顺序表的基本操作:void main()
{
char a[5]={'a','b','c','d','e'};
int n=5;
char f='f',b='a',e;
SqList sq;
InitList(sq); //初始化表
CreateList(sq,a,n); //传入数据
DispList(sq); //输出表
printf("sq.length=%d\n",ListLength(sq)); //输出表长
if(ListEmpty(sq)) //判断是否为空表
printf("sq是空表\n");
else
printf("sq不是空表\n");
printf("a在第%d位\n",LocateElem(sq,b)); //按元素值查找
ListInsElem(sq,f,4); //在第4个位置上插入f元素
DispList(sq); //输出表
printf("\n");
DelElem(sq,3,e); //删除第三个元素
DispList(sq); //输出表
}
其他函数和链表结构体定义包在头文件中。
Q3: 如何用C语言编写一个链表?
可以用结构体和指针来实现
定义:
定义一个单个元素的结构
typedef struct Chain_tag { // 这里用typedef来定义,方便使用
int data; // 这里的数据可以是任意类型
//其他数据
struct Chain_tag *prev, *next;// 由于Chain为不完全类型,故只能用指针的方式声明
} Chain;
使用:
用单个结构体的指针作为head
#include malloc.h
//Chain的定义写在这里
Chain *
alloc_single_chain(int data /*, (其他参数)*/)
{
Chain *tmp;
tmp = malloc(sizeof(Chain));
tmp.data = data;
//...其余数据初始化
tmp.prev = tmp.next = NULL; // 将前后指针置为NULL
return tmp;
}
void
dispose_chain(Chain *target) //其实这里功能简单,用宏实现也可以
{
free(target);
return;
}
int main()
{
Chain *head;
Chain *pos;
head = alloc_single_chain(10);//初始化起始结点
head-next = alloc_single_chain(11);//同理。。下一个结点
for (pos = head; pos; pos = pos-next)//清理垃圾好习惯
{
dispose_chain(pos);
}
return 0;
}
这里有几点要注意:
由于链表用指针来实现,故不要忘记分配内存
垃圾清理时一定要从起始结点开始依次向后释放,以防内存泄漏
c语言链表结构体主函数的介绍就聊到这里吧,感谢你花时间阅读本站内容,更多关于c语言链表和结构体、c语言链表结构体主函数的信息别忘了在本站进行查找喔。







