The Go language implements sequential storage of linear table instances

  • 2020-05-26 09:19:34
  • OfStack

This article illustrates how the Go language implements sequential storage of linear tables. Share with you for your reference. The details are as follows:

The code is as follows:

/////////
// Store linear tables sequentially
////////
package main
import "fmt"
const MAXSIZE = 20 // Define array length
// Defines a linear table structure
type List struct {
    Element [MAXSIZE]int // An array that stores the elements of a linear table
    length  int          // Linear table length
}
// Initializes the linear table ,d: The initial element , l location
func (l *List) InitList(d int, p int) {
    l.Element[p] = d
    l.length++
}
// Insert elements
//d: Inserted data
//p: Insert the location
func (l *List) Insert(d int, p int) bool {
    if p < 0 || p >= MAXSIZE || l.length >= MAXSIZE {
        return false
    }
    if p < l.length {
        for k := l.length - 1; k >= p; k-- {
            l.Element[k+1] = l.Element[k]
        }
        l.Element[p] = d
        l.length++
        return true
    } else {
        l.Element[l.length] = d
        l.length++
        return true
    }
}
// Remove elements
//p: Delete the location of the element
func (l *List) Delete(p int) bool {
    if p < 0 || p > l.length || p >= MAXSIZE {
        return false
    }
    for ; p < l.length-1; p++ {
        l.Element[p] = l.Element[p+1]
    }
    l.Element[l.length-1] = 0
    l.length--
    return true
}
func main() {
    var l List
    i := 0
    b := 1
    // Initialize the 1 A linear table
    for i < 15 {
        l.InitList(b, i)
        i++
        b++
    }
    // insert 1 An element
    l.Insert(1, 13)
    // delete 1 An element
    l.Delete(5)
    fmt.Println(l)
}

I hope this article has been helpful to your programming of Go language.


Related articles: