• 自己写的,用c语言实现的一个数组存储的线性表


    #include <iostream>
    #include <iterator>  

    #include <string> 

    #include <vector>
    #include <deque>
    #include <list>
    #include <algorithm>
    #include <map>
    #include <set>
    #include <stack>

    using namespace std;
    //动态内存
    typedef struct tagElement
    {
    int x;
    int y;
    } NODE;

    int init_size = 100;
    int add_size = 10;

    NODE *first = NULL;
    int num = 0;
    int size = 0;

    void init()//初始化
    {
     first = (NODE*)malloc(init_size * sizeof(NODE));
        num = 0;
     size = init_size;
    }

    void Add(NODE node)//未尾增加一个元素
    {
       if (num == size)
       {
          first = (NODE*)realloc(first, (init_size + add_size) * sizeof(NODE));
       init_size += add_size;
       
       }

       first[num] = node;
       num++;
    }

    void Print()
    {
     for (int i = 0; i < num; i++)
     {
      cout<<first[i].x<<endl;
      cout<<first[i].y<<endl;
     }
    }

    void Insert(int index, NODE node)//插入一个元素
    {
     if (index > num)//以0开头的索引,如果大于元素数目,则退出程序
     {
      exit(1);
     }

     if (index == num)//如果索引号和元素数目相等,则直接在未尾加上
     {
      Add(node);
      return ;
     }
     
     if (num == size)//如果正好元素的数目和内存大小相等,则扩张内存
     {
          first = (NODE*)realloc(first, (init_size + add_size) * sizeof(NODE));
       init_size += add_size;   
     }


     for (NODE *end = &first[num - 1]; end >= &first[index]; --end)//从最后一个元素遍历到要插入的元素的位置
     {
      *(end + 1) = *end;
     }

     first[index] = node;//注意,在c/c++中*(a+i) = a[i] = *(i+a),实际上a[i]就是*(a+i)的简写
     num++;
    }

    void Get(int index,NODE *node)//得到索引的值
    {

     if (index > num-1)
     {
           exit(1);
     }

     *node = first[index];
    }

    void Remove(int index)//删掉某索引的值
    {
     if (index > num-1)
     {
           exit(1);
     }

     for (int i = index; i < num - 1; i++)
     {
      first[i] = first[i + 1];
     }

     num--;
    }

    void Append(NODE *node, int total)//两个线性表合并,另一个线性表的首指针是node,num个元素
    {
        first = (NODE*)realloc(first, (total + num) * sizeof(NODE));
       
     for (int i = 0; i < total; i++)
     {
      first[num + i] = node[i];
     }


    }
    void main()//测试
    {

    NODE n;
    n.x = 1;
    n.y = 2;

    NODE n1;
    n1.x = 3;
    n1.y = 4;

    Add(n);
    Add(n1);

    Print();

    NODE n3;
    n3.x = 12;
    n3.y = 15;
    Insert(0,n3);

    Print();

    Remove(1);

    Print();


    }

  • 相关阅读:
    git教程学习笔记(1)
    一句话懂什么是JS闭包
    attachEvent和addEventListener 的使用方法和区别
    地址栏中多个问号如何处理
    事件委托用法
    rem和em的区别
    echarts事件中获取当前实例
    this经典试题
    获取浏览器选中文本并操作
    android Activity launch mode 一个实例 singleInstance
  • 原文地址:https://www.cnblogs.com/lizhengjin/p/1348742.html
Copyright © 2020-2023  润新知