• c实现的list


    // clist.cpp : 定义控制台应用程序的入口点。
    //

    #include "stdafx.h"
    #include <stdio.h>
    #include <malloc.h> //动态分配内存
    #include <stdlib.h> //exit 函数
    #include <stdbool.h> //布尔值函数
    #include <string.h>

    struct node {
        char * str;
        int len;
        node* next;
        //node* first;
        //node* last;
    };

    node* first = NULL;
    node* last = NULL;
    node* prev = NULL;
    node* search(const char * str);


    /*node* del(node* list) {
        if (list == NULL)
            return;
        free(list->str);
        return list->next;
    }*/

    node* new_node() {
        node* n = (node*)malloc(sizeof(node) + 1);
        return n;
    }

    node* first_node() {
        return first;
    }

    node* last_node() {
        return last;
    }

    void delete_node(const char* str) {
        node* node_to_del = search(str);
        prev->next = node_to_del->next;
        free(node_to_del->str);
        node_to_del->str = NULL;
        free(node_to_del);
        node_to_del = NULL;
        prev = first;
    }

    void update(const char* str, const char* newstr) {
        node* node_to_update = search(str);
        strcpy(node_to_update->str, newstr);
        node_to_update->len = strlen(newstr);
        node_to_update->str[node_to_update->len] = '';
    }

    node* list_init(const char* first_string) {
        first = last = new_node();
        first->str = (char*)malloc(sizeof(first_string)+1);
        strcpy(first->str, first_string);
        first->len = strlen(first_string);
        first->str[first->len] = '';
        first->next = NULL;
        return first;
    }

    void add(const char * str) {
        node* n = new_node();
        n->str = (char*)malloc(sizeof(str)+1);
        n->next = NULL;
        n->len = strlen(str);
        n->str[n->len] = '';
        strcpy(n->str, str);
        last->next = n;
        last = n;
    }

    node* search(const char * str) {
        node* n = first;
        prev = first;
        while (n != NULL && n->next != NULL) {
            if (strcmp(str, n->str) == 0)
                return n;
            prev = n;
            n = n->next;
        }
        return n;
    }

    int main()
    {
        node* head = list_init("head");
        add("hello,first");
        add("hello,second");
        add("cc");
        add("dd");
        add("ee");
        add("ea");
        add("eb");
        add("ec");
        add("ed");
        add("ee");

        node* dd_node = search("ee");
        delete_node("ee");
        update("hello,second", "second");
        return 0;
    }


  • 相关阅读:
    第四次作业—四则运算
    第四次作业—代码规范
    【欢迎来怼】事后诸葛亮会议
    软件工程——第七次作业
    第17次Scrum会议(10/29)【欢迎来怼】
    软件工程——第六次作业
    第10次Scrum会议(10/22)【欢迎来怼】
    软件工程——第五次作业
    欢迎来怼——第四次Scrum会议
    软件工程——第四次作业(3)
  • 原文地址:https://www.cnblogs.com/yuanxiaoping_21cn_com/p/8611926.html
Copyright © 2020-2023  润新知