重写链表
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Data
{
int id;
char name[15];
}Data;
typedef struct Node
{
struct Data data;
struct Node *next;
}Node;
//创建链表并初始化
struct Node *CreateHead( Node **head)
{
if(NULL==head)
return;
*head=(Node *)malloc(sizeof(Node) );
if(NULL==*head)
return;
(*head)->next=NULL;
(*head)->data.id=0;
(*head)->data.name[0]='\0';
return *head;
}
//头插
int Insert_tail(Node *head,Data data)
{
Node *newnode=(Node *)malloc(sizeof(Node) );
newnode->data.id=data.id;
strcpy(newnode->data.name,data.name);
while(head->next!=NULL)
{
head=head->next;
}
head->next=newnode;
newnode->next=NULL;
return 1;
}
//打印函数
void print(Data *data)
{
printf("id=%d,name=%s\n",data->id,data->name);
}
//打印所有数据
void Dispaly(Node *head)
{
while(head->next!=NULL)
{
print((&head->next->data));
head=head->next;
}
}
//删除
int Delete(Node *head,Data data)
{
while(head->next!=NULL)
{
if(head->next->data.id==data.id)
{
Node *temp=head->next;
head->next=temp->next;
free(temp);
temp=NULL;
//return -1;
}
head=head->next;
}
return 1;
}
//链表长度
int Length(Node *head)
{
int i;
while(head->next!=NULL)
{
i++;
head=head->next;
}
return i;
}
int main()
{
struct Node *head;
struct Data data1={10,"ggjj"};//给数据结构值
struct Data data2={11,"ggjj"};
struct Data data3={12,"ggjj"};
struct Data data4={13,"ggjj"};
int i;
CreateHead(&head);
Insert_tail(head,data1);
Insert_tail(head,data2);
Insert_tail(head,data3);
Insert_tail(head,data4);
i=Length(head);
printf("长度是%d\n",i);
Dispaly(head);
printf("\n");
Delete(head,data1);
Dispaly(head);
return 0;
}
总结
之前学了链表同时也用链表写了一些程序,但是这次重写链表我觉得我对链表还是不懂,就连第一步链表初始化都不会写了。我想我对链表的理解还是不够,我还得努力去学他。