本周主要学习了结构体,位段,联合体和单链表的创建(头插法,尾插法,任意位置插入);
结构体声明:
括号里为成员列表
括号外为变量列表
typedef:
重命名,方便后面引用。
结构体内存对齐:
需要注意的:
对齐数=编译器默认的一个对齐数与该成员大小的较小值;
结构体总大小为成员列表中最大对齐数的整数倍;
结构体镶套:镶套的结构体对齐到自己最大对齐数的整数倍;同时整个结构体的大小是所有最大对齐数的整数倍;
位段:
位段的内存分配是按照类型的比特位创建一个内存块,按照冒号后的数字(比特位)来填充,如果填不下就在开创一个新空间接着填
位段的优点是能节省空间,但同时也存在很多不确定因素。
枚举:
枚举如果不给里面的成员赋值,默认从第一位开始为0自增下去;
联合体:
命名和结构体相似;
同时上面的了联合体大小为4字节;
联合体所占的空间不仅取决于最宽成员,还跟所有成员有关系,即其大小必须满足两个条件:
(1)大小足够容纳最宽的成员;
(2)大小能被其包含的所有基本数据类型的大小所整除。
联合体的所占空间为成员列表中最大对齐数的整数倍;
需要注意的如果成员列表中存在数组,比如char a[5];此时这个成员的对齐数为1不为5(对齐数是类型大小);
链表:
链表是物理存储单元上非连续的、非顺序的存储结构,数据元素的逻辑顺序是通过链表的指针地址实现,有一系列结点(地址)组成,结点可动态的生成。
NULL可以用来标记最后一个块;
尾插法的代码:
//尾插法
#include
#include
typedef struct node {
int data;
struct node* next;
}node;
node* head = NULL;
int count = 0;
void print()
{
node* temp = head;
printf("你的链表是:");
while (temp!= NULL)
{
printf("%d", temp->data);
temp = temp->next;
}
printf("\n");
}
void insert(int num)
{
count++;
node* temp = (node*)malloc(sizeof(node));
temp->data = num;
temp->next = NULL;
if (count == 1)
{
head = temp;
}
node* temp1 = head;
while (temp1->next!= NULL)
{
temp1 = temp1->next;
}
if (count != 1)
{
temp1->next = temp;
}
}
int main()
{
int num = 0;
while (1)
{
printf("请输入你要插入的数字(输入0终止):");
if (num == 0)
{
break;
}
scanf_s("%d", &num);
insert(num);
print();
}
}
头插法:
//头插法
#include
#include
typedef struct node {
int data;
struct node* next;
}node;
node* head=NULL;
void print(int x)
{
struct node* temp = head;
printf("链表是:");
while (temp != NULL)
{
printf("%d", temp->data);
temp = temp->next;
}
printf("\n");
}
void insert(int x)
{
struct node* temp = (struct node*)malloc(sizeof(struct node));
temp->data = x;
temp->next = head;
head = temp;
}
int main()
{
int x = 0;
while(1)
{
printf("请输入链表中的数字(输入0终止):");
scanf_s("%d", &x);
if (x == 0)
{
return 0;
}
insert(x);
print(x);
}
}
任意位置插入:
//任一位置插入
//任一位置插入
#include
#include
typedef struct node{
int data;
struct node* next;
}node;
node* head = NULL;
void print()
{
node* temp = head;
printf("你的链表是:");
while (temp != NULL)
{
printf("%d", temp->data);
temp = temp->next;
}
printf("\n");
}
void insert(int num, int pos)
{
node* temp1 = (node*)malloc(sizeof(node));//申请的内存块的地址的活全部交给temp1;
temp1->data = num;
if (pos == 1)
{
temp1->next = head;
head = temp1;
return;
}
node* temp2 = head;
for (int i = 0; i < pos - 2; i++)
{
temp2 = temp2->next;
}
temp1->next = temp2->next;
temp2->next = temp1;
}
int main()
{
int num = 0;
int pos = 0;
int count = 0;
while(1)
{
printf("请输入你想插入的数和插入的位置(第一个数默认插入1号位,输入0 0则终止):");
scanf_s("%d %d", &num, &pos);
if (num == 0 && pos == 0)
{
return 0;
}
if (count == 0 && pos != 1)
{
pos = 1;
count++;
}
insert(num, pos);
print();
}
}