#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//typedef int DATA;
typedef enum{TRUE,FALSE,ERROR}BOOL;
typedef struct Data
{
int id;
char name[15];
}DATA;
typedef struct Node
{
struct Data data;
struct Node *next;
}Node;
/* struct Node* CreateHead()
{
Node* head = (Node*)malloc(sizeof(Node)/sizeof(char));
head->next = NULL;
if(NULL == head)
{
return ;
}
return head;
} */
struct Node* CreateHead2(struct Node **head)
{
if(head == NULL)
{
return ;
}
*head = (Node *)malloc(sizeof(Node)/sizeof(char));
(*head)->next =NULL;//优先级问题
if(*head == NULL)
{
return ;
}
return *head;
}
BOOL Insert_tail(struct Node *head,struct Data data)
{
if(NULL == head)
{
return ERROR;
}
Node *p = (Node*)malloc(sizeof(Node)/sizeof(char));
p->next = NULL;
if(NULL == p)
{
return ERROR;
}
p->data.id = data.id;
strcpy(p->data.name,data.name);
Node *tmp = head;
while(head->next!=NULL)
{
head = head->next;
}
p->next = head->next;
head->next = p;
return TRUE;
}
void Display(Node *head)
{
if(NULL == head)
{
return ;
}
Node *tmp = head->next;
while(tmp!=NULL)
{
printf("id: %d\n",tmp->data.id);
printf("name: %s\n",tmp->data.name);
tmp = tmp->next;
}
}
BOOL Delete(Node *head,struct Data data)
{
if(NULL ==head)
{
return ERROR;
}
while(head!=NULL)
{
if(head->next->data.id == data.id)
{
Node *tmp = head->next;
head->next = tmp->next;
free(tmp);
return TRUE;
}
head = head->next;
}
return FALSE;
}
int Length(Node *head)
{
if(NULL == head)
{
return ;
}
int count = 0;
Node *tmp = head->next;
while(tmp!=NULL)
{
tmp = tmp->next;
count++;
}
return count;
}
int main()
{
Node *head = NULL;
head = CreateHead2(&head);
//Node *pNode = CreateHead();
if(NULL!=head)
{
printf("创建成功\n");
}
DATA test={1,"ll"};
DATA test2 = {2,"yy"};
Insert_tail(head,test);
Insert_tail(head,test2);
Display(head);
Delete(head,test2);
//Display(pNode);
int count = Length(head);
printf("长度: %d\n",count);
return 0;
}
又又又又写一遍链表
最新推荐文章于 2023-03-11 12:19:57 发布