线性表的链式存储结构的特点是用一组任意的存储单元存储线性表的数据元素,这组线性单元可以是连续的,也可以是不连续的。
线性表的顺序存储结构的特点是逻辑关系上相邻的两个元素在物理位置上也相邻,因此可以随机存取表中任意元素。然而,对于顺序表进行插入、删除操作时需要通过移动数据元素来实现,影响了运行效率。而线性表的链式存储结构不需要用地址连续的存储单元来实现,因此它不要求逻辑上相邻的两个数据元素位置上也相邻,它是通过“链”建立起数据元素之间的逻辑关系,因此对线性表的插入、删除运算不需要移动数据元素。
链表可以分为单链表、循环单链表、双向链表。
package main
import (
"fmt"
)
type Node struct {
value interface{}
next *Node
}
type LinkedList struct {
Size int
First *Node
}
var linkedList *LinkedList = &LinkedList{}
/**
在头部添加元素
*/
func Add(value interface{}) {
node := &Node{}
node.value = value
link := linkedList.First
if link == nil {
linkedList.First = node
linkedList.Size++
}else {
node.next = link
linkedList.First = node
linkedList.Size++
}
}
/**
获取指定位置元素
*/
func Get(i int) interface{} {
if i > linkedList.Size {
return nil
}
first := linkedList.First
var node *Node
index := 1
for first != nil && first.next != nil && index < i {
first = first.next
index++
}
if first == nil{
return nil
}
node = first
return node.value
}
//返回迭代数据
func Iterator() (iter []interface{}) {
first := linkedList.First
if first == nil {
return
}
iter = append(iter,first.value)
for first.next != nil {
first = first.next
iter = append(iter,first.value)
}
return
}
//清空链表
func Flush() bool {
if linkedList.First != nil {
linkedList.First = nil
linkedList.Size = 0
}
return true
}
/**
在尾部添加元素
*/
func Append(value interface{}) interface{} {
first := linkedList.First
for first != nil && first.next != nil{
first = first.next
}
if first == nil {
linkedList.First = &Node{value: value}
linkedList.Size++
return value
}
var node *Node = &Node{value: value}
first.next = node
linkedList.Size++
return value
}
//删除元素
func Del(i int) interface{}{
if i > linkedList.Size {
return nil
}
if i == 1 && linkedList.First != nil {
v := linkedList.First.value
linkedList.First = linkedList.First.next
linkedList.Size--
return v
}
first := linkedList.First
index := 1
for first != nil && first.next != nil && index < i-1 {
first = first.next
}
if first == nil{
return nil
}
node := first
if node.next != nil && node.next.next != nil {
v := first.next.value
first.next = first.next.next
linkedList.Size--
return v
}
v := first.value
first.next = nil
linkedList.Size--
return v
}
//获取链表的大小
func Size() int {
return linkedList.Size
}
func main() {
/*Add("a")
Add("b")
Add("c")
Add("d")
Add("e")*/
//fmt.Println(linkedList.First.value)
/*fmt.Println(linkedList.First.next.value)
fmt.Println(linkedList.First.next.next.value)
fmt.Println(linkedList.First.next.next.next.value)*/
var n int = 0
for i :='a'; i <= 'z'; i++{
n++
Append(fmt.Sprintf("%c",i))
}
fmt.Println("-------------",Size())
fmt.Println("---------------------------")
Flush()
fmt.Println("-------------",Size())
fmt.Println("======================================")
for i,v := range Iterator(){
fmt.Printf("i=%d,v=%v\n",i,v)
}
}