1.斐波那契數列
代碼:
package fib
//求斐波那契數列第n項
func PrintFib(n int)int {
if n <= 0 {
return 0
}
if n >= 3 {
return PrintFib(n - 1) + PrintFib(n - 2)
} else {
if n == 1 {
return 0
}
if n == 2 {
return 1
}
}
return 0
}
2.迴文鏈表:
(1).自己簡單實現鏈表結構
package linkedList
//定義鏈表
type LinkedList struct {
Value string //值
NextAddress *LinkedList //下一個地址
Len int //長度
}
//將切片初始化爲鏈表
func (linkedList LinkedList)Init(parameter []string)*LinkedList {
var newLinkedList *LinkedList
for i := len(parameter) - 1; i >= 0; i-- {
newLinkedList = doInit(newLinkedList,parameter[i])
}
newLinkedList.Len = len(parameter)
return newLinkedList
}
func doInit(nextAddress *LinkedList,value string) *LinkedList {
linkedList := LinkedList{
Value: value,
NextAddress: nextAddress,
}
return &linkedList
}
(2).進行迴文判斷
package main
import (
linkedList2 "awesomeProject/pkg/linkedList"
"fmt"
)
func main() {
var l linkedList2.LinkedList
parameter := []string{"1","2","3","2","1"}
linkedList := l.Init(parameter)
linkedLen := linkedList.Len
leftMap := map[int]string{}
flag := true
for i := 0; i < linkedLen; i++ {
fmt.Println(linkedList.Value)
if i <= linkedLen/2 {
//按長度等分,如果是左邊部分,則放入map
leftMap[i] = linkedList.Value
}
if i >= linkedLen/2 {
//按長度等分,如果是右邊部分,則比較
if linkedList.Value != leftMap[linkedLen - i - 1] {
flag = false
}
}
linkedList = linkedList.NextAddress
}
fmt.Println(flag)
}