练习1:
单链表:
1.创建 2.头插 3.头删 3.尾插 4.尾删 5.判空 6.输出 7.按位置插入 8.按位置删除
#include"link_list.h"
//创建单链表,实际上是创建头结点
node_p create_link_list()
{
node_p H=(node_p)malloc(sizeof(node));
if(H==NULL)
{
printf("空间申请失败\n");
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)
{
printf("空间申请失败\n");
return NULL;
}
new->data=data;
return new;
}
//头插
void insert_head(node_p H,int data)
{
//入参合理性检查
if(H==NULL)
{
printf("入参为空\n");
return;
}
node_p new=create_node(data);
new->next=H->next;
H->next=new;
H->data++;
}
//单链表判空
int empty_link(node_p H)
{
if(H==NULL)
{
printf("入参为空\n");
return -1;
}
return H->next==NULL?1:0;
}
//输出
void show_link(node_p H)
{
if(H==NULL)
{
printf("入参为空\n");
return;
}
if(empty_link(H))
{
printf("表为空\n");
return;
}
node_p p=H->next;
while(p!=NULL)
{
printf("%d->",p->data);
p=p->next;
}
printf("NULL\n");
}
//头删
void delete_head(node_p H)
{
if(H==NULL)
{
printf("入参为空\n");
return;
}
if(empty_link(H))
{
printf("表为空\n");
return;
}
node_p del=H->next;//保存要删除的结点
H->next=H->next->next;//将H指向下一个节点
free(del);//释放要删除的结点
}
//尾插
void insert_tail(node_p H,int data)
{
if(H==NULL)
{
printf("入参为空\n");
return;
}
//找到尾结点
node_p p=H;
//判断尾结点的条件:指针域指空
while(p->next!=NULL)
{
p=p->next;
}
node_p new=create_node(data);
new->next=p->next;
p->next=new;
H->data++;
}
//尾删
void delete_tail(node_p H)
{
if(H==NULL)
{
printf("入参为空\n");
return;
}
if(empty_link(H))
{
printf("表为空\n");
return;
}
node_p p=H;
while(p->next->next!=NULL)
{
p=p->next;
}
node_p del=p->next;
p->next=p->next->next;
free(del);
H->data--;
}
//按位置插入
void insert_pos(node_p H,int data,int pos)
{
if(H==NULL)
{
printf("入参为空\n");
return;
}
if(pos<=0||pos>H->data+1)
{
printf("输入不合理\n");
return;
}
node_p temp=H;
for(int i=0;i<pos-1;i++)
{
temp=temp->next;
}
node_p new=create_node(data);
new->next=temp->next;
temp->next=new;
H->data++;
}
//按位置删除
void delete_pos(node_p H,int pos)
{
if(H==NULL)
{
printf("入参为空\n");
return;
}
if(empty_link(H))
{
printf("表为空\n");
return;
}
if(pos<=0||pos>H->data)
{
printf("输入不合理\n");
return;
}
node_p temp=H;
for(int i=0;i<pos-1;i++)
{
temp=temp->next;
}
node_p temp2=temp->next;
temp->next=temp->next->next;
free(temp2);
H->data--;
}
练习2:
求以下结构体大小
1.指定最大对齐2字节
2.char x 1字节
3.struct A
{
short a; 2字节
int *b; 8字节
char c; 1字节
}
4.long b;8字节
因为指定对齐为2字节所以最后结果为1+(1)+11+(1)+8=22
()括号里面为根据指定对齐补的内存