zoukankan      html  css  js  c++  java
  • [数据结构]之顺序表

    [数据结构]之顺序表

    描述
    顺序表:是指在一段连续的存储单元存储数据的线性表。多使用数组来实现。

    数据结构

    1 属性:

    最大长度 CAP

    当前长度 Length

    存储数组 Elements


    2 操作:

    Get(index) 获取元素

    Insert(index,elem) 插入元素

    Delete(index) 删除第index个元素

    ## 实现
    使用go语言实现代码如下:

        package main
        
        import (
            "fmt"
        )
        
        const CAP = 20
        
        type SqList struct {
            elemets [CAP]string
            length  int
        }
        
        /*
         *    获取顺序表的第index元素
         */
        func (list *SqList) Get(index int) (string, error) {
            if list.length == 0 || index < 0 || index > list.length-1 {
                return "", fmt.Errorf("the index %d Out Of Bounds", index)
        
            }
            return list.elemets[index], nil
        }
        
        /*
         *    插入顺序表元素,在第index位置
         */
        func (list *SqList) Insert(index int, elem string) error {
            if list.length == CAP {
                return fmt.Errorf("the list is full")
            }
            if index < 0 || index > list.length {
                return fmt.Errorf("the index %d Out Of Bounds", index)
            }
            //如果不是在最后插入,需要移动后面的元素
            if index < list.length {
                for i := list.length - 1; i >= index; i-- {
                    list.elemets[i+1] = list.elemets[i]
        
                }
            }
            list.elemets[index] = elem
            list.length++
            return nil
        }
        
        /*
         *    删除顺序表元素,在第index位置
         */
        func (list *SqList) Delete(index int) error {
            if list.length == 0 {
                return fmt.Errorf("the list is empty")
            }
            if index < 0 || index > list.length {
                return fmt.Errorf("the index %d Out Of Bounds", index)
            }
            //如果不是在最后删除,需要移动后面的元素
            if index < list.length {
                for i := index; i < list.length; i++ {
                    list.elemets[i] = list.elemets[i+1]
        
                }
            }
        
            list.length--
            return nil
        }
        
        func main() {
        
            list := &SqList{}
        
            list.Insert(0, "AAAAA")
            list.Insert(1, "BBBBB")
            list.Insert(2, "CCCCC")
        
            list.Delete(1)
        
            for i := 0; i < list.length; i++ {
                elem, _ := list.Get(i)
                fmt.Printf("get elem %d value:%v
    ", i, elem)
            }
        }
  • 相关阅读:
    deepin系统换软件下载源&商店卡死刷新空白问题解决
    php数组和json数组之间的互相转化
    php 获取数组个数的方法
    php 三种文件下载的实现
    win10激活
    deepin/linux安装exe
    deepin连接windows
    deepin升级微信
    deepin安装.net core
    在Deepin 15.9下安装Wine 4.0
  • 原文地址:https://www.cnblogs.com/sxt102400/p/3234231.html
Copyright © 2011-2022 走看看