package main
import (
"strings"
"strconv"
"fmt"
)
/**
雙向鏈表
*/
type DoubleLinkedList struct {
//鏈表頭節(jié)點
head *Node
//鏈表尾部節(jié)點
tail *Node
//長度
size int
}
/**
遍歷器接口
*/
type Interater interface{
/**
是否還有下一個
*/
hasNext() bool
/**
下一個節(jié)點
*/
next() *Node
}
/**
遍歷器
*/
type ListInterater struct {
list *DoubleLinkedList
currentNode *Node
}
/**
遍歷器是否還有下一個節(jié)點
*/
func (inter *ListInterater) hasNext() bool{
if inter.currentNode==nil && inter.list.head!=nil {
return true
}else if inter.currentNode==nil && inter.list.head==nil {
return false
}else{
return inter.currentNode.next!=nil
}
}
/**
遍歷器獲取下一個節(jié)點
*/
func (inter *ListInterater) next() *Node{
if inter.currentNode==nil && inter.list.head!=nil{
inter.currentNode = inter.list.head
}else if(inter.currentNode==nil && inter.list.head==nil){
return nil
}else{
inter.currentNode = inter.currentNode.next
}
return inter.currentNode
}
/**
節(jié)點
*/
type Node struct {
data interface{}
prev *Node
next *Node
}
func (list *DoubleLinkedList) GetHead() *Node {
return list.head
}
func (list *DoubleLinkedList) GetTail() *Node {
return list.tail
}
func (list *DoubleLinkedList) Size() int {
return list.size
}
func (list *DoubleLinkedList) initFromNode(node *Node) {
list.head = node
list.tail = node
list.size = 1
}
func (list *DoubleLinkedList) addHead(node *Node){
oldHead :=list.head
oldHead.prev = node
node.next = oldHead
node.prev = nil
list.head = node
list.size++
}
/**
獲取鏈表的遍歷器
*/
func (list *DoubleLinkedList) Iterater() *ListInterater{
inter:=ListInterater{
list:list,
currentNode:nil,
}
return &inter
}
/**
從頭部添加節(jié)點
*/
func (list *DoubleLinkedList) AddFromHead(node *Node) {
if list.head==nil && list.tail==nil {
list.initFromNode(node)
}else{
list.addHead(node)
}
}
/**
從尾部添加節(jié)點
*/
func (list *DoubleLinkedList) addTail(node *Node){
oldTail :=list.tail
oldTail.next = node
node.prev = oldTail
node.next = nil
list.tail = node
list.size++
}
/**
刪除指定位置節(jié)點
*/
func (list *DoubleLinkedList) Remove(index int) {
node:=list.Get(index)
if node==nil {
return
}
prev:=node.prev
next:=node.next
if prev!=nil {
prev.next=next
}
if next!=nil {
next.prev=prev
}
list.size--
}
/**
從后面追加節(jié)點
*/
func (list *DoubleLinkedList) Append(node *Node) {
if list.head==nil && list.tail==nil {
list.initFromNode(node)
}else{
list.addTail(node)
}
}
/**
獲取指定位置節(jié)點
*/
func (list *DoubleLinkedList) Get(index int) *Node {
next:=list.head
for i:=0;i
文章題目:go實現(xiàn)雙向鏈表并使用iterater遍歷
文章地址:
http://weahome.cn/article/jchpho.html