结构体
声明一个结构体类型,创建结构体变量
struct stu{
char name[10];
char sex[10];
int age;
}s1,s2,s3;//全局结构体变量
struct stu s4;//全局结构体变量
int main()
{
struct stu s5;//局部结构体变量
}
结构体初始化
struct stu s={'Li',"男",18};
结构体内存偏移
内存对齐是为了更方便的读取数据,空间被浪费,但效率被提高
结构体指针
p=&x;//不正确,两个结构体类型不同
链表
静态链表,动态链表
头结点不保存任何数据
无头链表:第一个结点存放数据(表头不定)
有头链表:第一个结点不存放数据
静态链表
struct Node
{
int data;
struct Node *next;
};
如何遍历链表?
先定义一个指针变量,指向头结点
再while循环输出
指针移动到下一元素的首地址
直到指向NULL停止
动态链表
#include <stdio.h>
#include <stdlib.h>
struct Node
{
int date;
struct Node* next;
};
struct Node*creatlist()
{
struct Node* headNode=(struct Node*)malloc(sizeof(struct Node));
headNode->next=NULL;
return headNode;
};
struct Node*creatNode(int date)
{
struct Node*newNode=(struct Node*)malloc(sizeof(struct Node));
newNode->date=date;
newNode->next=NULL;
return newNode;
};
void printList(struct Node*headNode)
{
struct Node*Pmove=headNode->next;
while(Pmove)
{
printf("%d",Pmove->date);
Pmove=Pmove->next;
}
printf("\n");
}
void insert_Node_By_HeadNode(struct Node*headNode,int date)
{
struct Node*newNode=creatNode(date);
newNode->next=headNode->next;
headNode->next=newNode;
}
int main()
{
struct Node*list=creatlist();
insert_Node_By_HeadNode(list,1);
insert_Node_By_HeadNode(list,2);
insert_Node_By_HeadNode(list,3);
printList(list);
}
创建链表
首先创建表头---->等于创建结构体变量
结构体指针变成结构体变量 需要动态内存申请
struct Node* creatlist()
{
struct Node* headNode = (struct Node*)malloc(sizeof(atruct Node))//申请动态内存
//初始化
headNode->next = NULL;
return headNode;
}
创建结点
//创建结点
struct Node *createNode(int data)
{
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}
打印结点数据
void printf(struct Node* headNode)
{
struct Node*p = headNode->next;
while(p!=NULL)
{
printf("%d",p->data);
p=p->next;
}
printf("\n");
}
插入(表头)
void insert(struct Node*headNode,int data)
{
//创建插入的新节点
struct Node* newNode = createNode(data);
newNode->next=headNode->next;
headNode->next=newNode;
}
测试
int main()
{
struct Node* list = createHead();
for(int i=0;i<3;i++)
{
insertNodeByHead(list,i);
}
print(list);
return 0;
}
//结果为2,1,0
删除指定位置数据
枚举
把可能的取值一一列举出来
如:一周的七天,月份有12个
enum Sex
{//括号内放的是枚举的可能取值--常量
male,//默认0开始
female,//1
secret//2
};//只能取这三个值
共用体
union un
{
char c;
int i;
}u;
sizeof(u)//大小为占字节数最大的成员