用c语言写单链表

#include <stdio.h>
#include <malloc.h>




//the node
struct NodeN{
    int data;
    struct NodeN *next;
};


typedef struct NodeN *Node;


void init(Node *Lp);//为甚么不一样。*lp与l
void insert(Node L,int data);
int isExist(Node L,int data);//**************************
void del(Node L,int data);
void print(Node L);
void destroy(Node L);
Node search(Node L,int data);
Node locate(Node L,int data);


void init(Node *Lp) {
    Node tmp = (struct NodeN *)malloc(sizeof(struct NodeN));
    tmp->next = NULL;    //empty linked list
    tmp->data = -999;   //first head
    *Lp = tmp;//
    return;
}


void insert(Node L,int data) {
    Node tmp = (struct NodeN *) malloc(sizeof(struct NodeN));
    tmp->data = data;
    if(L->next == NULL) { // empty  
        tmp->next = NULL;
        L->next = tmp;
    } else {
        Node p = locate(L,data);
        tmp->next = p->next;
        p->next = tmp;
    }
}


void del(Node L,int data) {
    Node tmp = search(L,data);//*************
    Node del = tmp->next;
    if(NULL != tmp) { //I find it****************
        tmp->next = tmp->next->next;
        free(del);
    }
}


Node search(Node L,int data) {//***************
    Node tmp = L;
    while(tmp->next != NULL) {
        if(tmp->next->data == data) {
            return tmp;
        }
        tmp = tmp->next;
    }
    return NULL;
}


Node locate(Node L,int data) {//*********************
    Node tmp = L;
    while(tmp->next != NULL) {
        if(tmp->next->data > data) {
            return tmp;//*******
        }
        tmp = tmp->next;
    }
    return tmp;
}


void print(Node L) {
    Node tmp = L->next;
    while(tmp!=NULL) {
        printf("data is %d\t",tmp->data);
        printf("next address is %d",tmp->next);
        printf("\n");
        tmp = tmp->next;
    }
}


void destroy(Node L) {
    if(L->next!=NULL)
        destroy(L->next);


    free(L);
}


int main() {
    Node L1;
    init(&L1);
    insert(L1,10);
    insert(L1,5);
    insert(L1,8);
    del(L1,8);
    print(L1);
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值