golang实现单链表
2024-08-30 23:42:51
package main import "fmt" type Object interface{} type Node struct {
data Object
next *Node
} type List struct {
headNode *Node
} func NewNode(data Object, next *Node) *Node {
return &Node{data, next}
} func (list *List) IsEmpty() bool {
return list.headNode == nil
} func (list *List) Add(node *Node) *List {
headNode := list.headNode
if headNode.next != nil {
node.next = headNode.next
}
headNode.next = node
return list
} func (list *List) Append(node *Node) *List {
if list.IsEmpty() {
list.headNode = node
return list
}
curNode := list.headNode
for curNode.next != nil {
curNode = curNode.next
}
curNode.next = node
return list
} func (list *List) Insert(index int, data Object) {
if (index >= && index < list.Length()) {
count :=
if !list.IsEmpty() {
curNode := list.headNode
for curNode != nil && count < index {
count++
curNode = curNode.next
}
node := NewNode(data, curNode.next)
curNode.next = node
}
}
} func (list *List) Remove(index int) {
if (index >= && index < list.Length()) {
count :=
if !list.IsEmpty() {
curNode := list.headNode
for curNode != nil && count < index- {
count++
curNode = curNode.next
}
curNode.next = curNode.next.next
}
}
} func PrintList(list *List) {
cur := list.headNode
for cur != nil {
fmt.Println(cur.data)
cur = cur.next
}
} func (list *List) Length() int {
var length int
curNode := list.headNode
for curNode != nil {
length++
curNode = curNode.next
}
return length
} func ReverseList(head *Node) *Node {
cur := head
var pre *Node = nil
for cur != nil {
pre, cur, cur.next = cur, cur.next, pre
}
return cur
} func main(){
fmt.Println("NewNode======================")
node := NewNode(, nil)
fmt.Println(node.data)
list := &List{node}
PrintList(list)
node2 := NewNode("a", nil)
list.Append(node2)
fmt.Println("Add======================")
PrintList(list)
node1 := NewNode(, nil)
list.Add(node1)
fmt.Println("Length======================")
PrintList(list)
fmt.Println(list.Length())
fmt.Println("Insert======================")
list.Insert(, )
PrintList(list)
fmt.Println("Remove======================")
list.Remove()
PrintList(list)
fmt.Println("ReverseList======================")
ReverseList(node)
PrintList(list)
}
最新文章
- CentOS安装JDK-1.7
- [Oracle]快速插入大量(100w)数据
- 关于Application.Lock和Lock(obj) 转 http://www.cnblogs.com/yeagen/archive/2012/03/01/2375610.html
- 用ticons指令结合ImageMagickDisplay工具批量生成Android适应图片
- 1.1-java创建包和类的方法
- VC++6.0 显示行号
- 老调重弹:对kvo的封装思路
- 黄聪:MYSQL提交一批ID,查询数据库中不存在的ID并返回
- Web Forms vs Web MVC
- 在Xcode中使用C++与Objective-C混编
- PIC16SCM设置不同IO功耗端口状态的影响
- .Net async
- Win10安装Ubuntu14.04.5双系统(显示器为DP接口)
- SQLServer之创建索引视图
- 一码阻塞,万码等待:ASP.NET Core 同步方法调用异步方法“死锁”的真相
- 【js】event(事件对象)详解
- partial.js client-side routing(客户端路由-基于HTML5 SPA特性的历史API)
- ES系列十二、ES的scroll Api及分页实例
- c# 使用checked和unchecked
- CentOS6.5搭建ldap及pdc的过程