Golang实现单链表数据结构

·  阅读 394
Golang实现单链表数据结构

代码

package main

import (
   "errors"
   "fmt"
)

// 单链表
type Object interface {
}

type Node struct {
   Data Object
   Next *Node
}

type List struct {
   head *Node
}

func (l *List) IsEmpty() bool {
   if l.head == nil {
      return true
   } else {
      return false
   }
}

func (l *List) Len() int {
   var len int = 0
   if l.IsEmpty() {
      return 0
   }
   n := l.head
   for {
      len++
      n = n.Next
      if n == nil {
         break
      }
   }
   return len
}

func (l *List) HeadAdd(data interface{}) {
   head := &Node{
      Data: data,
      Next: l.head,
   }
   l.head = head
}

func (l *List) Append(data interface{}) {
   if l.IsEmpty() {
      l.head = &Node{
         Data: data,
      }
      return
   }
   cur := l.head
   for {
      if cur.Next == nil {
         cur.Next = &Node{
            Data: data,
         }
         break
      } else {
         cur = cur.Next
      }
   }

}

func (l *List) Index(index int, data interface{}) {
   if index == 0 {
      l.HeadAdd(data)
      return
   }
   if index > l.Len() {
      fmt.Println(errors.New("index大于链表的长度,返回原链表"))
      return
   }
   cur := l.head
   for i := 1; i < index; i++ {
      cur = cur.Next
   }
   next := cur.Next
   //cur为插入节点的上一个 ,next为插入节点的下一个
   cur.Next = &Node{
      Data: data,
      Next: next,
   }
}

func (l *List) DeleteData(data interface{}) {
   cur := l.head
   if data == cur.Data {
      l.head = l.head.Next
   } else {
      for cur.Next != nil {
         if cur.Next.Data == data {
            cur.Next = cur.Next.Next
         } else {
            cur = cur.Next
         }
      }
   }
}

func (l *List) DeleteIndex(index int) {
   if index == 0 {
      l.head = l.head.Next
   }
   cur := l.head
   i := 0
   for cur.Next != nil {
      i++
      if index == i {
         cur.Next = cur.Next.Next
      } else {
         cur = cur.Next
      }

   }
}

func (l *List) FindData(data interface{}) (int, error) {
   cur := l.head
   if cur.Data == data {
      return 0, nil
   }
   var index int = 0
   for cur.Next != nil {
      index++
      if cur.Next.Data == data {
         return index, nil
      }else {
         cur = cur.Next
      }
   }
   return 0, errors.New("没有找到对应的data")
}

func (l *List) ShowList() {
   //打印链表
   if l.IsEmpty() {
      fmt.Println("")
      return
   }

   fmt.Print(l.head.Data)
   cur := l.head
   for i := 0; i < l.Len(); i++ {
      cur = cur.Next
      if cur != nil {
         fmt.Print(" -> ")
         fmt.Print(cur.Data)
      }
   }
   fmt.Println("")
}

func main() {
   var l List
   l.HeadAdd(1)
   l.ShowList()
   l.Append(3)
   l.ShowList()
   l.Append(5)
   l.ShowList()
   l.Index(1, 40)
   l.ShowList()
   l.DeleteData(40)
   l.ShowList()
   //l.DeleteIndex(2)
   //l.ShowList()
   fmt.Println(l.FindData(5))
}
复制代码

结果

>go run SingleList.go
1
1 -> 3
1 -> 3 -> 5
1 -> 40 -> 3 -> 5
1 -> 3 -> 5
2 <nil>
复制代码
分类:
后端
标签:
收藏成功!
已添加到「」, 点击更改