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

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

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;
}
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值