关闭

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

标签: c语言链表-头插法尾插法
139人阅读 评论(0) 收藏 举报
分类:
#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;
}
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:7520次
    • 积分:277
    • 等级:
    • 排名:千里之外
    • 原创:21篇
    • 转载:2篇
    • 译文:0篇
    • 评论:2条