package main
import "fmt"
//链表和数据结构
type Node struct{
data string
next *Node
}
type List struct{
Head *Node
}
//链表是否为空
func (this *List) IsEmpty() bool{
if this.Head == nil {
return true
}
return false
}
//链表长度
func (this *List) Length() int{
if this.IsEmpty() {
return 0
}
node := this.Head
count := 0
for node != nil{
node = node.next
count ++
}
return count
}
//从头部添加元素
func (this *List) Add(data string){
node := &Node{data:data}
node.next = this.Head
fmt.Println(this.Head)
this.Head = node
fmt.Println(this.Head)
}
//从尾部添加元素
func (this *List) Append(data string){
//先储存数据
node := &Node{data:data}
//判断是否为空
if this.IsEmpty() {
this.Head = node
}else{
list := this.Head
for list.next != nil{
list = list.next
}
list.next = node
}
}
//插入到指定位置
func (this *List) InsertNode(index int , data string) bool{
if index < 0 {
this.Add(data)
}else{
pre := this.Head
count := 0
for count < (index -1) {
pre = pre.next
count++
}
//把pre的下个节点指针给了node
node := &Node{data:data}
node.next=pre.next
pre.next = node
}
return true
}
//删除节点中所有相等的数据
func (this *List) removeNode(data string) bool{
list := this.Head
if list.data == data {
this.Head = list.next
}else{
for list.next != nil {
if list.next.data == data{
list.next = list.next.next
}else{
list = list.next
}
}
}
return true
}
//查找
func (this *List) findNode(data string) int{
list := this.Head
var count = 0
for list != nil {
count ++
if list.data == data {
return count
}
list = list.next
}
return count
}
//循环链表
func (this *List) foreach(){
node := this.Head
for node != nil {
fmt.Println(node.data)
node = node.next
}
}
//链表反转
func (this *List) reseve() *Node{
node := this.Head
var pre *Node
for node !=nil{
node.next, pre, node = pre, node, node.next
}
return pre
}
//打印指定链表
func printNode(node *Node){
for node != nil{
fmt.Println(node.data)
node = node.next
}
}
func main(){
list := &List{}
list.Add("data")
list.Append("hello")
list.Append("world")
list.foreach()
pos := list.findNode("hello")
fmt.Println(pos)
newList := list.reseve()
printNode(newList)
}