C语言实现单链表

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

typedef struct _NODE{
    int data;
    struct _Node *next;
}Node;

/*
建立带有头结点的单向链表,循环创建结点,结点数据域中的数值从键盘输入,
以 -1 作为输入结束标志,链表的头结点地址由函数值返回.
*/
Node* init_linkedlist(){
    Node* head = NULL;
    head = (Node*)malloc(sizeof(Node));
    if(head == NULL){
        return NULL;
    }
    head->data = -1;
    head->next = NULL;
    Node* curNode = head;
    int data=-1;
    while(1){
        printf("please input data:\n");
        scanf("%d", &data);
        if(data == -1){
            break;
        }
        Node* temp = (Node*) malloc(sizeof(Node));
        temp->data = data;
        temp->next = NULL;
        curNode->next = temp;
        curNode = curNode->next;
    }
    return head;
}

/*
    遍历列表
*/
void foreach(Node* head){
    if(head == NULL){
        return;
    }
    Node* temp = head->next;
    while(temp != NULL){
        printf("%d\n", temp->data);
        temp = temp->next;
    }
}

/*
    插入节点
    在指定值后面插入数据data,如果值val不存在,则在尾部插入
*/
void insert(Node* head, int val, int data){
    if(head == NULL){
        return;
    }
    Node* pre = head;
    Node* temp = pre->next;
    while(temp != NULL){
        if(temp->data == val){
            break;
        }
        pre = temp;
        temp = temp->next;
    }
    Node* newNode = (Node*)malloc(sizeof(Node));
    newNode->data = data;
    if(temp == NULL){
        printf("不存在值为%d的节点!\n", val);
        pre->next = newNode;
        return;
    }
    newNode->next = temp->next;
    temp->next = newNode;

}

/*
    删除节点
*/
void delete(Node* head, int val){
    if(head == NULL){
        return;
    }
    Node* pre = head;
    Node* cur = pre->next;
    while(cur != NULL){
        if(cur->data == val){
            break;
        }
        pre = cur;
        cur = cur->next;
    }
    if(cur != NULL){
        Node* temp = cur;
        pre->next = cur->next;
        free(temp);
        temp->next = NULL;
    }
}

/*
    销毁列表
*/
void destroy(Node* head){
    if(head == NULL){
        return;
    }
    Node* pre = head;
    Node* cur = pre->next;
    while(cur != NULL){
        Node* temp = cur;
        cur = cur->next;
        pre->next = cur;
        free(temp);
        temp->next = NULL;
    }
}
void test(){
    Node* head = init_linkedlist();
    insert(head, 5, 6);
    foreach(head);
    delete(head, 5);
    foreach(head);
    destroy(head);
}
int main(){
    test();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值