(算法)对数组进行旋转操作

在写lua 虚拟机时 碰到旋转 操作 研究了下
在这里插入图片描述
在这里插入图片描述

package main
type lists struct {
	top int
	slots []interface{}
}
func main(){
	ls := lists{14,nil}
	for i := 0;i<ls.top;i++ {
		ls.slots = append(ls.slots, i);
	}
	ls.Rotate(2,-2)
}

func (self *lists) reverse(from,to int){
	slots := self.slots
	for from < to {
		slots[from],slots[to] = slots[to],slots[from]
		from ++
		to --
	}
}
func (self *lists) Rotate(idx,n int) {
	//获取栈顶元素
	t := self.top -1
	//获取指定索引元素
	p := idx
	var m int
	if n >= 0 {
		m = t - n
	}else {
		m = p - n - 1
	}
	self.reverse(p,m)
	self.reverse(m+1,t)
	self.reverse(p,t)
}
发布了67 篇原创文章 · 获赞 5 · 访问量 3166

猜你喜欢

转载自blog.csdn.net/weixin_41315492/article/details/103495924