双向链表

#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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值