牙家零少

编程的目的并不是赞美计算机可以做什么,而是赞美富有创造力的人们在计算机的辅助下可以做什么...

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;
}
阅读更多
个人分类: c 数据结构与算法
上一篇c++网络多人五子棋
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭