欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

c语言链表,头插法和尾插法

程序员文章站 2023-08-29 17:44:23
#include #include #include typedef struct stdata{ int e; }data; typedef struct s...
#include 
#include 
#include 

typedef struct stdata{
    int e;
}data;

typedef struct stlink{
    data data;
    struct stlink* next;
}link;

struct link* create(){
    link* head = (link*)malloc(sizeof(link));
    memset(&head->data,0,sizeof(link));
    head->next = null;
    return head;
}

void head_insert(link* head,data e){
    link *ptemp,*pnew;
    if (head->data.e != 0){
        ptemp = head->next;
        pnew = (link*)malloc(sizeof(link));
        memcpy(&pnew->data,&e,sizeof(data));
        pnew->next = ptemp;
        head->next = pnew;
    }else{
        memcpy(&head->data,&e,sizeof(data));
    }
}

void nial_insert(link* head,data e){
    link *ptemp,*pnew;
    ptemp = head;
    if (head->data.e != 0){
        pnew = (link*)malloc(sizeof(link));
        memcpy(&pnew->data,&e,sizeof(data));
        while(ptemp->next != null)
            ptemp = ptemp->next;
        ptemp->next = pnew;
        pnew->next = null;
    }
    else{
        memcpy(&head->data,&e,sizeof(data));
    }
}

void dele(link* head,data e){
    link *pbefore = head;
    link *ptemp = head;
    while(ptemp->next != null){
        if (ptemp->data.e == e.e)
        {
            link *pdel = ptemp;
            pbefore->next = ptemp->next;
            pdel->next = null;
            free(pdel);
            return;
        }else{
            pbefore = ptemp;
            ptemp = ptemp->next;
        }
    }
    if (ptemp->data.e == e.e)
    {
        link *pdel = ptemp;
        pbefore->next = ptemp->next;
        pdel->next = null;
        free(pdel);
    }
}

void show(link* head){
    link *ptemp = head;
    while(ptemp->next != null){
        printf("%d \n",ptemp->data.e);
        ptemp = ptemp->next;
    }
    printf("%d \n",ptemp->data.e);
}

int main()
{
    link *head = create();
    data e1={1001},e2={1002},e3={1003},e4={1004};
    //head_insert(head,e1);
    //head_insert(head,e2);
    //head_insert(head,e3);
    //head_insert(head,e4);
    nial_insert(head,e1);
    nial_insert(head,e2);
    nial_insert(head,e3);
    nial_insert(head,e4);
    show(head);
    printf("dele------------\n");
    dele(head,e2);
    show(head);
    return 0;
}