使用Golang实现一个单链表,功能包括获取链表长度,头节点,尾节点,插入节点和删除节点。
package slist
import "fmt"
type SingleNode struct {
Value interface{}
next *sNode
}
func (sn *SingleNode) Next() *SingleNode {
if sn != nil {
return sn.next
}
return nil
}
type SingleList struct {
head *SingleNode
len int
}
func NewSingleList() *SingleList {
return &SingleList{}
}
func (sl *SingleList) Len() int {
return sl.len
}
func (sl *SingleList) Front() *SingleNode {
return sl.head
}
func (sl *SingleList) Back() *SingleNode {
p := sl.head
for p.next != nil {
p = p.next
}
return p
}
func (sl *SingleList) PushFront(node *SingleNode) *SingleNode {
node.next = sl.head
sl.head = node
sl.len++
return node
}
func (sl *SingleList) PushBack(node *SingleNode) *SingleNode {
if sl.len == 0 {
sl.head = node
sl.len++
return node
}
p := sl.head
for p.next != nil {
p = p.next
}
p.next = node
sl.len++
return node
}
func (sl *SingleList) InsertBefore(node, before *SingleNode) *SingleNode {
p := sl.head
for p != nil && p.next != before {
p = p.next
}
return sl.insert(node, p)
}
func (sl *SingleList) InsertAfter(node, after *SingleNode) *SingleNode {
return sl.insert(node, after)
}
func (sl *SingleList) insert(node, at *SingleNode) *SingleNode {
next := at.next
at.next = node
node.next = next
sl.len++
return node
}
func (sl *SingleList) insertVal(val interface{}, at *SingleNode) *SingleNode {
node := new(SingleNode)
node.Value = val
return sl.insert(node, at)
}
func (sl *SingleList) Remove(node *SingleNode) interface{} {
if sl.len == 0 || node == nil {
return nil
}
if node == sl.head {
p := sl.head
sl.head = sl.head.next
sl.len--
return p.Value
}
p := sl.head
for p != nil && p.next != node {
p = p.next
}
if p == nil {
return nil
}
p.next = p.next.next
sl.len--
return node.Value
}
func (sl *SingleList) String() string {
s := fmt.Sprintf("Len: %d Value:", sl.len)
for p := sl.head; p != nil; p = p.Next() {
s += fmt.Sprintf("->%v", p.Value)
}
return s
}