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)
            }
        }
  • 相关阅读:
    BZOJ 3251 树上三角形:LCA【构成三角形的结论】
    BZOJ 2442 [Usaco2011 Open]修剪草坪:单调队列优化dp
    2018湖南省赛选拔
    扩展BSGS-传送门
    倒数第N个字符串
    HDU-6070 Dirt Ratio(二分+线段树+分数规划)
    第一场多校
    HDU5923-Prediction-有继承味道的并查集
    POJ2516费用流
    POJ3436:ACM Computer Factory-最大流
  • 原文地址:https://www.cnblogs.com/sxt102400/p/3234231.html
Copyright © 2011-2022 走看看