PracticeDev/study_go/datastruct/linklist.go

106 lines
1.4 KiB
Go
Raw Normal View History

2022-12-20 17:31:11 +08:00
package main
import "fmt"
type linkNode struct {
value int
next *linkNode
}
type linkList struct {
head *linkNode
}
func newLinkList() *linkList {
return &linkList{
head: nil,
}
}
func (l *linkList) Print() {
for node := l.head; node != nil; node = node.next {
fmt.Printf("%d ", node.value)
}
fmt.Println()
}
func (l *linkList) Add(value int) {
node := &linkNode{
value: value,
next: nil,
}
if l.head == nil {
l.head = node
return
}
for n := l.head; n != nil; n = n.next {
if n.next == nil {
n.next = node
return
}
}
}
func (l *linkList) Adds(value ...int) {
for _, v := range value {
l.Add(v)
}
}
func (l *linkList) LeftShift(n int) {
if n <= 0 {
return
}
var prev *linkNode
for i, node := 0, l.head; node != nil; i, node = i+1, node.next {
if i == n {
l.head = node
prev.next = nil
break
}
prev = node
}
}
func (l *linkList) LeftShiftCycle(n int) {
if n <= 0 {
return
}
var prev *linkNode
for i, node := 0, l.head; node != nil; i, node = i+1, node.next {
if i == n {
l.head = node
prev.next = nil
break
}
prev = node
}
}
func (l *linkList) Inverse() {
var prev *linkNode
for node := l.head; node != nil; {
next := node.next
node.next = prev
prev = node
node = next
}
l.head = prev
}
func main() {
l := newLinkList()
l.Adds(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
l.Print()
//l.Inverse()
l.LeftShiftCycle(3)
l.Print()
}