创建单链表
//创建单链表实际上是创建头节点
typedef struct node
{
int data; //数据域
struct node *next; //指针域,指向整个数据结构
}node,*node_p;
node_P create_link_list()
{
node_p H = (node_p)malloc(sizeof(node));
if(H==NULL)
{
//申请失败
return NULL;
};
H->data = 0; //刚创建链表时,链表中没有节点
H->next = NULL; //链表中没有节点,头结点指向空
return H;
}
//创建节点,创建数据节点
node_P create_node(int data)
{
node_p new = (node_p)malloc(sizeof(node));
if(new==NULL)
{
//申请失败
return NULL;
};
new->data = data;
return new
}
头插
void insert_head(node_p H,int data)
{
//入参合理性检查
if(H==NULL)
{
入参为空
return;
};
//给输入的数据申请存储空间
node_p new = create_node(data);//返回堆区申请的空间的首地址
new->next = H->next; //新节点的指针域,指向原来头结点,指向的节点
H->next = new //头节点指向新节点
};
判空
int empty_link(node_ H)
{
//入参合理性检查
if(H==NULL)
{
//入参为空
return -1;
};
return H->next == NULL ? 1 : 0;
}
输出
void show_link(node_p H)
{
if(H==NULL)
{
//入参为空
return;
};
if(empty_link(H))
{
//表为空
return
};
node_p p = H->next //从头节点的下一个节点开始输出
//最后一个节点需要进入循环并输出
while(p!=NULL)
{
printf("%d->"p->data);
p = p->next;//让指针p指向下一个节点
}
printf("NULL\n")//换行
}
头删
void dele_link(node_p H)
{
if(H==NULL)
{
//入参为空
return;
};
if(empty_link(H))
{
//表为空
return
};
node_p del = H->nex;//保存要删除的结点
H->nex = h->next->next;//让头节点指向第二个节点
free(del);//释放要删除的结点
H->data--;//链表长度减少
}
尾插
void insert_tail(node_p H, int data)
{
if(H==NULL)
{
//入参为空
return;
};
node_p p = H;
//找到尾节点
while(p->next!=NULL)
{
p=p->next;//p指向下一个节点
};
node_p new = create_node(data);
//让新节点的指针域指向原来尾节点的指针域
new->next = p->next;
//原来的尾节点指向新节点
p->next = new;
H->data++;
};
尾删
void dele_tail(node_p H)
{
if(H==NULL)
{
//入参为空
return;
};
if(empty_link(H))
{
//表为空
return
};
node_p p = H;
//当不是尾部的时候,让指针向前移动,直到找到倒数第二个节点
while(p->next->next!=NULL)
{
p = p->next;
};
//保存要删除的节点
node_p del = p->next;
// p->next->next是NULL
p->next = p->next->next;
free(del);
H->data--;
}
按位置插入
void insert_pos(node_p H, int data, int pos)
{
if(H==NULL)
{
//入参为空
return;
};
//判断位置不合理的情况
//如果有5个元素,往第6个位置插入相当于尾插
if( pos > H->data+1 || pos <=0)
{
//位置不合理
return;
};
//pos是多少,就让next移动几次
int i //纪录位置
node_p p = H;//让指针从头节点触发
for(i=0; i<pos-1; i++)
{
p = p->next
};
//申请新节点
node_p new = create_node(data);
//让新节点的指针指向原来pos位置的节点
new->next = p->next;
//让pos-1位置的节点指向新节点
p->next = new;
H->data++;
}
按位置删除
// 删除第二个位置,也就是2
// 1 2 3 4
// 1 3 4
void dele_pos(node_p H, int pos)
{
if(H == NULL)
{
printf("入参为空\n");
return;
};
if(empty_link())
{
printf("链表为空\n");
return;
};
//判断参数合法
if( pos > H->data || pos <=0)
{
//位置不合理
return;
};
//for 起始位置是头节点(0),结束位置是pos-1
node_p p = H,
int i = 0;
//循环前进
for(i;i<pos-1;i++)
{
p = p->next;
};
//循环结束,到达了需要删除的位置,保存删除项
node_p del = p;
//删除需要把当前位置的值赋值成下一个位置?
p->next = p->next->next;
//释放删除项
free(del);
H->data--;
}
文件结构
//求以下结构体大小
#pragma pack(2) //指定两字节对齐
typedef struct
{
char x; //1 //1
struct A
{
short a; //2
int *b; //8
char c; //1 //1
}p; //12 //拿本身是对齐量和操作系统对齐量计算
long b; //8
}T;
#pragma pack()
14+8 = 22