#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <malloc.h>
//double linked list create:
typedef struct DBNode
{
char name[15];
struct DBNode *next;
struct DBNode *prior;
}dbnode,*dblistptr;
struct DBNode * create_of_dnode(int n)
{
dblistptr head,p,p_last;
head = (struct DBNode *)malloc(sizeof(struct DBNode)); //初始化头结点
head->name[0] = '\0';
head->next = NULL;
head->prior = NULL;
p_last = head; //初始化last指针
printf("please input names:\n");
for(int i=0; i<n; i++)
{
p = (dblistptr)malloc(sizeof(dbnode)); //建立新节点,并始终保持p_last指向链表末,p指向新节点;
p_last->next = p;
p->prior = p_last;
printf("please input the %d student's name: ",i+1);
scanf("%s",p->name);
p->next = NULL;
p_last = p;
}
return head;
};
//查找元素
struct DBNode* search(dbnode *h, char *s)
{
dbnode *p = h;
while(p != NULL)
{
if(strcmp(p->name, s) == 0)
{
return p;
}
p = p->next;
}
printf("Cannot find data!\n");
return NULL;
};
//删除元素
void delt(dbnode *tar)
{
if(tar ->next == NULL)
{
tar->prior->next = NULL;
free(tar);
}
else
{
tar->prior->next = tar->next;
tar->next->prior = tar->prior;
free(tar);
}
};
int main()
{
int number;
dblistptr to_search,head,tmp;
char name[20];
printf("please input the number :");
scanf("%d", &number);
head = create_of_dnode(number);
tmp = head;
while(tmp)
{
printf("%s ", &*(tmp->name));
tmp = tmp->next;
}
printf("\nplease input the element to search:\n");
scanf("%s",name);
to_search = search(head,name);
printf("the name you want to find is: %s", &*(to_search->name));
delt(to_search);
tmp = head;
printf("\nNow the list is:\n");
while(tmp = tmp->next)
{
printf("%s -", *&tmp->name);
}
printf("NULL\n");
return 0;
}
双向链表
最新推荐文章于 2025-07-20 12:45:35 发布