数据结构单链表创建,插入,修改,遍历,查找以及删除,销毁(附源文件)
程序员文章站
2022-03-22 19:22:09
...
代码源文件
链接失效私聊我
结构体定义标题
typedef struct inform //数据域结构体
{
char name[20];
char num[20];
int score[3];
}DATA;
typedef struct Node //节点结构体
{
DATA data; //数据域
struct Node *next; //指针域
}Node;
头节点创建
/头节点创建
Node* list_create(DATA data)
{
Node* head = (Node*)malloc(sizeof(Node));
if(head == NULL)
{
printf("内存申请失败!\n");
return NULL;
}
head->data = data;
head->next = NULL;
return head;
}
头插法
//头插法
Node* list_addhead(Node* head,DATA data)
{
if(head == NULL)
{
return list_create(data);
}
Node* p = (Node*)malloc(sizeof(Node));
if(p == NULL)
{
printf("内存申请失败!\n");
return head; //创建失败,返回原来头节点指针
}
p->data = data; //结构体之间可以直接相互赋值
p->next = head;
head = p;
return head;
}
尾插法
//尾插法
Node* list_addtail(Node* head,DATA data)
{
Node *p = head;
if(head == NULL)
{
return list_create(data);
}
Node* tail = (Node*)malloc(sizeof(Node));
if(tail == NULL)
{
printf("内存申请失败!\n");
return head; //创建失败,返回原来头节点指针
}
tail->data = data;
tail->next = NULL;
while(p->next != NULL)
{
p = p->next;
}
p->next = tail;
return head;
}
Node* list_addtail_v2(Node* head,DATA data)
{
Node* pNew = (Node*)malloc(sizeof(Node));
if(pNew == NULL)
{
printf("内存申请失败!\n");
return head; //创建失败,返回原来头节点指针
}
pNew->data = data;
pNew->next = NULL;
Node* p = head, *q;
while(p != NULL)
{
q = p;
p = p->next;
}
if(head != NULL)
{
q->next = pNew;
}
else
{
head = pNew;
}
return head;
}
查找(姓名)删除
//查找(姓名)删除
Node* list_delete(Node* head, char* ch)
{
if(head == NULL)
{
return NULL;
}
Node* p = head,*q = NULL;
if(memcmp(p->data.name,ch,sizeof(p->data.name))==0)
{
head = p->next;
free(p);
return head;
}
while(p != NULL)
{
if(memcmp(p->data.name,ch,sizeof(p->data.name)) == 0)
{
q->next = p->next;
free(p);
return head;
}
q = p;
p = p->next;
}
puts("不存在");
return head;
}
头删
//头删
Node* list_delhead(Node* head)
{
Node* p = head->next;
free(head);
head = p;
return head;
}
尾删
//尾删
void list_deltail(Node* head)
{
Node* p = head,*q = NULL;
while(p->next != NULL)
{
q = p;
p = p->next;
}
free(p);
q->next = NULL;
}
链表长度
//链表长度
int list_long(Node* head)
{
Node* p = head;
int i = 0;
while(p)
{
p = p->next;
i++;
}
return i;
}
链表逆序
/链表逆序
Node* list_reverse(Node* head)
{
if(head == NULL)
{
return head;
}
Node* p = head->next,*q = NULL;
head->next = NULL;
while(p != NULL)
{
q = p;
p = p->next;
q->next = head;
head = q;
}
return head;
}
链表遍历
//链表遍历
void list_print(Node* head)
{
Node *p = head;
int num = sizeof(p->data.score)/sizeof(p->data.score[0]);
if(head == NULL)
{
return;
}
while(p != NULL)
{
printf("%-15s %-15s ",p->data.name,p->data.num);
for(register int i = 0; i < num; i++)
{
printf("%-4d ",p->data.score[i]);
}
printf("\n");
p = p->next;
}
}
销毁链表
void list_destroy(Node** head) //销毁链表
{
Node *p = *head;
while(p != NULL)
{
p = (*head)->next;
free(*head);
*head = p;
}
head = NULL;
}