双向链表:next指向下一个节点,front指向前一个节点
双链表原理图:
// main.c
// 双链表
// Created by fzl
// Copyright © fzl All rights reserved.
//
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct NB
{
int class;
char name[20];
}NB;
typedef struct LINK
{
NB data;
struct LINK *front;
struct LINK *next;
}LINK,*pLINK;
/*
创建双链表
*/
pLINK createDlist(pLINK head)
{
if(head==NULL)
{
head=(pLINK)malloc(sizeof(LINK));
head->front=NULL;
head->next=NULL;
}
return head;
}
NB getData()
{
NB nb;
printf("请输入信息[班级 姓名]:");
scanf("%d%s",&nb.class,nb.name);
return nb;
}
/**
插入信息:头插,
*/
pLINK insertData(pLINK head)
{
if(head==NULL)
{
head=createDlist(head);
}
pLINK p=(pLINK)malloc(sizeof(LINK));
p->data=getData();
if(head->next==NULL)
{
p->next=head->next;
head->next=p;
p->front=head;
return head;
}
p->next=head->next;
head->next->front=p;
head->next=p;
p->front=head;
return head;
}
/*
打印数据
*/
void printData(pLINK head)
{
if(head==NULL||head->next==NULL)
{
printf("无信息打印\n");
return;
}
pLINK temp=head->next;
for (; temp!=NULL; temp=temp->next)
{
printf("[%d %s]----->",temp->data.class,temp->data.name);
}
printf("NULL\n");
}
void deleteData(pLINK head)
{
if(head==NULL||head->next==NULL)
{
printf("无信息删除\n");
return;
}
char name[20];
printf("请输入要删除人的姓名:");
scanf("%s",name);
pLINK temp;
for (temp=head->next; temp!=NULL; temp=temp->next)
{
if(strcmp(temp->data.name,name)==0)
{
pLINK front=temp->front;
pLINK next=temp->next;
front->next=next;
next->front=front;
free(temp);
return;
}
}
if(temp==NULL)
{
printf("查无此人\n");
}
}
int main()
{
pLINK head=NULL;
head=createDlist(head);
insertData(head);
insertData(head);
insertData(head);
printData(head);
deleteData(head);
printData(head);
return 0;
}