1.头部声明
#ifndef __LINK_LIST_H__
#define __LINK_LIST_H__
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct node
{
int data;
struct node *next;
}node,*node_p;
node_p create_link_list();
node_p create_node(int);
void insert_head(node_p,int);
int empty_link(node_p);
void show_link(node_p);
void dele_head(node_p);
void insert_tail(node_p,int);
void dele_tail(node_p);
void dele_pos(node_p,int);
#endif
2.自定义函数体
#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 new1 =create_node(data);
new1->next=H->next;
H->next=new1;
}
//判空
int empty_link(node_p H)
{
if(H==NULL)
{
printf("入参为空\n");
return 0;
}
return H->next==NULL?1:0;
}
//输出
void show_link(node_p H)
{
if(H==NULL)
{
printf("入参为空\n");
return;
}
node_p temp=H->next;
while(temp)
{
printf("%d\n",temp->data);
temp=temp->next;
}
}
//头删
void dele_head(node_p H)
{
if(H==NULL)
{
printf("入参为空\n");
return;
}
node_p w=H->next;
H->next=(H->next)->next;
free(w);
H->data--;
}
//尾插
void insert_tail(node_p H,int data)
{
if(H==NULL)
{
printf("入参为空\n");
return;
}
node_p temp=H;
while(temp->next!=NULL)
{
temp=temp->next;
}
node_p new2=create_node(data);
new2->next=temp->next;
temp->next=new2;
H->data++;
}
//按位置插入
void insert_pos(node_p H,int data,int pos)
{
if(H==NULL)
{
printf("入参为空\n");
return;
}
if(pos<0||pos>H->data)
{
printf("插入位置不合理\n");
}
int i=0;
node_p temp=H;
while(i<pos-1)
{
temp=temp->next;
i++;
}
node_p new3=create_node(data);
new3->next=temp->next;
temp->next=new3;
H->data++;
}
//按位置删除
void dele_pos(node_p H,int pos)
{
if(H==NULL)
{
printf("入参为空\n");
return;
}
if(pos<=1||pos>H->data+1)
{
printf("删除位置不合理\n");
}
int i=0;
node_p temp=H;
while(i<pos-2)
{
temp=temp->next;
i++;
}
node_p w=temp->next;
temp->next=temp->next->next;
free(w);
H->data--;
}
//尾删
void dele_tail(node_p H)
{
if(H==NULL)
{
printf("入参为空\n");
return;
}
node_p temp=H->next;
while(temp)
{
temp=temp->next;
}
node_p w=temp;
free(temp);
w=NULL;
H->data--;
}
3.主函数
#include "link_list.h"
int main(int argc, const char *argv[])
{
node_p H=create_link_list();
node_p new=create_node(100);
H->next=new;H->data++;
insert_head(H,90);
insert_tail(H,80);
for(int i=0;i<5;i++)
{
int temp;
scanf("%d",&temp);
insert_tail(H,temp);
}
dele_pos(H,4);
show_link(H);
return 0;
}
ubun
4.小题