单链表简介
单链表是一种顺序存储的结构。 有一个头结点,没有值域,只有连域,专门存放第一个结点的地址。 有一个尾结点,有值域,也有链域,链域值始终为NULL。 所以,在单链表中为找第i个结点或数据元素,必须先找到第i - 1 结点或数据元素,而且必须知道头结点,否则整个链表无法访问。
示例:
定义结构体
package main
import "fmt"
type Object
interface{}
type Node
struct {
Data Object
Next
*Node
}
type List
struct {
headNode
*Node
}
判断链表是否为空
func (this
*List)
ISEmpty() bool {
if this
.headNode
== nil {
return true
}else {
return false
}
}
获取链表长度
func (this
*List
) Length() int {
first
:= this
.headNode
count
:= 0
for first
!= nil {
count
++
first
= first
.Next
}
return count
}
从链表头部添加元素
func (this
*List
) Add(data Object
) *Node
{
node
:= &Node
{Data
: data
}
node
.Next
= this
.headNode
this
.headNode
= node
return node
}
从链表尾部添加元素
func (this
*List)
Append(data object)
{
node
:= &Node
{Data
: data
}
if this
.IsEmpty(){
this
.headNode
=node
}else {
cur
:= this
.headNode
for cur
.Next
!= nil {
cur
= cur
.Next
/链表进行位移,知道cur获取到尾节点
}
cur
.Next
= node
}
}
链表指定位置添加元素
func (this
*List)
Insert(index
int,data Object)
{
if index
< o
{
this
.Add(data
)
}else if index
> this
.Length(){
this
.Append(data
)
}else {
pre
:= this
.headNode
count
:= 0
for count
< (index
-1){
pre
= pre
.Next
count
++
}
node
:= &Node
{Data
: data
}
node
.Next
= pre
.Next
pre
.Next
= node
}
删除链表指定值的元素
func (this
*List
) Remove(data Object
){
pre
:= this
.headNode
if pre
.Data
== data
{
this
.headNode
= pre
.Next
}else {
for pre
.Next
!=nil {
if pre
.Next
.Data
== data
{
pre
.Next
= pre
.Next
.Next
} else {
pre
= pre
.Next
}
}
}
}
转载请注明原文地址:https://blackberry.8miu.com/read-39520.html