#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//链表代码总结
//数据
typedef struct data
{
int id;
char name[15];
}Data;
typedef struct node
{
Data data;
struct node *next;
}Node;
//头结点的创建及初始化
Node* CreatHead(Node **head)
{
//入口参数检查
if(NULL==head)
{
return ;
}
//申请空间,*head代表main函数的head
*head=(Node*)malloc(sizeof(Node)/sizeof(char));
if(*head==NULL)
{
return;
}
//申请内存的初始化
(*head)->next=NULL;
//返回内存的地址
return *head;
}
int Insert_tail(Node *head,Data data)
{
if(NULL==head)
{
return;
}
Node *node=(Node*)malloc(sizeof(Node)/sizeof(char));
if(NULL==node)
{
return;
}
node->data=data;
while(head->next!=NULL)
{
head=head->next;
}
head->next=node;
node->next=NULL;
return 1;
}
void Display(Node *head)
{
Node *tmp=head;
while(tmp->next!=NULL)
{
printf("%d\n",tmp->next->data.id);
printf("%s\n",tmp->next->data.name);
tmp=tmp->next;
}
}
int Delete(Node *head,Data data)
{
if(head==NULL)
{
return;
}
Node *tmp=head;
while(tmp->next!=NULL)
{
if((tmp->next->data.id==data.id)&&strcmp(tmp->next->data.name,data.name)==0)
{
Node *p=tmp->next;
tmp->next=tmp->next->next;
free(p);
p=NULL;
return 1;
}
tmp=tmp->next;
}
return -1;
}
int main()
{
Node *head=CreatHead(&head);
Data data1;
data1.id=1;
char a[10]="jdk";
strcpy(data1.name,a);
Insert_tail(head,data1);
Data data2;
data2.id=2;
char b[10]="abc";
strcpy(data2.name,b);
Insert_tail(head,data2);
Display(head);
Delete(head,data1);
printf("------------------\n");
Display(head);
return 0;
}
链表
最新推荐文章于 2023-09-12 18:07:10 发布