Go语言顺序表的实现

package main

import (
	"errors"
	"fmt"
)

const MaxSize int = 100

type SeqListClass struct {
	data []int
	length int
}

//为数组分配空间
func NewSeqList() *SeqListClass{
	if MaxSize == 0 {
		return nil
	}else{
		return &SeqListClass{
			data : make([] int, MaxSize, MaxSize),
			length : 0,
		}
	}
}

func (this *SeqListClass)CreateList(data []int, n int)error{
	for i := 0;i < n;i++{
		this.data[i] = data[i]
	}
	this.length = n
	return nil
}

func (this *SeqListClass)DispList()error{
	if this.length == 0{
		return errors.New("list length is 0!!!")
	}
	for i := 0;i < this.length;i++{
		fmt.Printf("%d ", this.data[i])
	}
	return nil
}

func (this *SeqListClass)ListLength()int{
	return this.length
}

func (this *SeqListClass)GetElem(i int)(int,error){
	if i < 0 || i > this.length{
		return -1, errors.New("out of range")
	}
	return this.data[i-1],nil
}

func (this *SeqListClass)LocateElem(value int)(int,error){
	var i int
	for i = 0;i < this.length;i++{
		if value == this.data[i]{
			break
		}
	}
	if i >= this.length{
		return -1, errors.New("out of range")
	}
	return i+1, nil
}

func (this *SeqListClass)ListInsert(i, value int)error{
	if i < 0 || i >= this.length{
		return errors.New("out of range")
	}
	for j := this.length;j >= i;j--{
		this.data[j] = this.data[j-1]
	}
	this.data[i] = value
	this.length++
	return nil
}

func (this *SeqListClass)ListDelete(i int)error{
	if i < 0 || i >= this.length{
		return errors.New("out of range")
	}
	for j := i;j < this.length;j++{
		this.data[j] = this.data[j+1]
	}
	this.length--
	return nil
}

func (this *SeqListClass)Reserve(){
	for i := 0;i < this.length/2;i++{
		tmp := this.data[i]
		this.data[i] = this.data[this.length - i - 1]
		this.data[this.length - i - 1] = tmp
	}
}

func main(){
	list := NewSeqList()
	data := []int{1,2,3,4,5,6,7,8,9,10}
	list.CreateList(data, 10)
	list.DispList()
	fmt.Printf("\n%d\n", list.ListLength())
	list.ListInsert(4,12)
	list.DispList()
	list.ListDelete(4)
	fmt.Printf("\n")
	list.DispList()
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值