数据结构学习笔记(一)
一、预备知识
0 读程序的步骤
0.0数据结构
- 数据结构是专门研究数据存储的问题
- 数据的存储包含两个方面:个体的存储+个体关系的存储
- 算法是对存储数据的操作
0.1 读程序的步骤
- 流程
- 功能
- 试数
1.指针
略
2.结构体
2.1为什么会出现结构体
①为了表示一些复杂的数据,而普通的基本类型无法满足要求
②在给所有变量添加一个共同的特征,那相关的变量联系起来
2.2什么叫结构体
结构体用户根据实际需要自己定义的复合数据类型
2.3如何使用结构体
- 定义
①通过结构体变量名来实现 st.sid
② **通过指向结构体变量的指针来实现 **
pst->sid // pst所指向的结构体变量中的sid这个成员
- 示例
#include<stdio.h>
#include<string.h>
struct Student
{
int sid;
char name[200];
int age;
}; //分号不能省略
int main(void)
{
sruct Student st ={10001,"ZhangSan",20}; //第一种方式
printf("%d %s %d\n",st.sid,st.name,st.age);
st.sid = 99; //第二种方式
st.name = "LiSi" // error
strcopy(st.name,"LiSi");
st.age=22;
printf("%d %s %d\n",st.sid,st.name,st.age);
struct Student *pst; //第三种方式 指针变量后边加->
pst =&st;
pst->sid =99; // pst->sid 等价于(*pst).sid 等价st.sid 所有 pst->sid等于st.sid
return 0;
}
2.4注意事项
①结构体变量不能加减乘除,但是可以相互赋值
②普通结构体变量和结构体指针变量作为函数传参的问题
③指针结构体的比较
#include <stdio.h>
#include <string.h>
struct Student
{
int sid;
char namep[200];
int age;
};
void f(struct Student *pst);
void g2(struct Student *pst);
void g(struct Student st);
int main(void)
{
struct Student st;
f(&st);
g(st);
return 0
}
void g(struct Student st) // 这种方式耗内存耗时间不推荐
{
printf("%d %s%d\n",st.sid,st.name,st.age);
}
void g2(struct Student *pst) // 通过传送指针的方式,减少运行时间和运行内存
{
printf("%d %s%d\n",pst->sid,pst->name,pst->age);
}
void f(struct Student *pst)
{
(*pst).sid =99;
strcpy(pst->name,"ZhangSan");
pst->age =22;
}
3.其他
3.1 动态内存分配
- 动态分配的内存,必须用free函数释放,否则不会释放
- 函数内的变量,当函数调用结束时,系统会收回该变量的存储
#include <stdio.h>
#include<malloc.h>
int main(void)
{
int a[5]= {4,10,2,8,6};
int len;
printf( "请输入你需要分配的数组的长度 :len="); //
scanf("%d",&len);
int *parr =(int *)malloc(sizeof(int)*len);// (int *)表示动态分配的地址为整形的地址
*parr=4; // parr[0] =4 // // 类似 a[0]=4
*(parr+1)=10; //等于 parr[1]=10; // 类似 a[1]=10
printf("%d %d\n",*parr,parr[1]);
free(parr) ; //把parr所代表的动态分配的20个字节的内存释放
return 0;
}
- 使用
#include <stdio.h>
#include<malloc.h>
int main(void)
{
int a[5]= {
4,10,2,8,6};
int len;
printf( "请输入你需要分配的数组的长度 :len="); //
scanf("%d",&len);
int *parr =(int *)malloc(sizeof(int)*len);// (int *)表示动态分配的地址为整形的地址
for(int i=0;i<len;++i)
scanf("%d",&parr[i]);
for(i=0;i<len;++i)
printf("%d\n",*(parr+i));
free(parr); //把parr所代表的动态分配的20个字节的内存释放
return 0;
}
3.2跨函数使用内存
下面的程序中,能够通过调用函数fun,使main函数中的变量指针P指向一个合法的整形单元的是(C)
A) main()
{
int *p;
fun(p);
...
}
int fun(int *p)
{
int s;
p=&s;
}
B) main()
{
int *p;
fun(&p);
...
}
int fun(int **q)
{
int s;
*q=&s;
}
C)#include<stdio.h>
main()
{
int *p;
fun(&p);
...
}
int fun(int **q)
{
*q=(int*)malloc(4);
}
D) main()
{
int *p;
fun(p);
...
}
int fun(int *p)
{
p=(int*)malloc(sizeof(int));
}
3.3 typedef
- 为变量类型重新赋一个名字
typedef int intl32;
intl32 t; // 等于int t
// 结构体的变形
typedef struct Student
{
int sid;
char name[10];
int age;
}ST;
ST st; //等于 struct Student st ;
//结构体的变形2
typedef struct Student
{
int sid;
char name[10]