golang实现单链表
数据结构
// Node represents a node of linked list
type Node struct {
value int
next *Node
}
// LinkedList represents a linked list
type LinkedList struct {
head *Node
len int
}
新增节点
在链表末尾增加节点
// Insert inserts new node at the end of from linked list
func (l *LinkedList) Insert(val int) {
n := Node{}
n.value = val
if l.len == 0 {
l.head = &n
l.len++
return
}
ptr := l.head
for i := 0; i < l.len; i++ {
if ptr.next == nil {
ptr.next = &n
l.len++
return
}
ptr = ptr.next
}
}
指定位置增加节点
// InsertAt inserts new node at given position
func (l *LinkedList) InsertAt(pos int, value int) {
// create a new node
newNode := Node{}
newNode.value = value
// validate the position
if pos < 0 {
return
}
if pos == 0 {
l.head = &newNode
l.len++
return
}
if pos > l.len {
return
}
n := l.GetAt(pos)
newNode.next = n
prevNode := l.GetAt(pos - 1)
prevNode.next = &newNode
l.len++
}
输出链表
// Print displays all the nodes from linked list
func (l *LinkedList) Print() {
if l.len == 0 {
fmt.Println("No nodes in list")
}
ptr := l.head
for i := 0; i < l.len; i++ {
fmt.Println("Node: ", ptr)
ptr = ptr.next
}
}
查找链表
// Search returns node position with given value from linked list
func (l *LinkedList) Search(val int) int {
ptr := l.head
for i := 0; i < l.len; i++ {
if ptr.value == val {
return i
}
ptr = ptr.next
}
return -1
}
获取指定位置的链表元素
// GetAt returns node at given position from linked list
func (l *LinkedList) GetAt(pos int) *Node {
ptr := l.head
if pos < 0 {
return ptr
}
if pos > (l.len - 1) {
return nil
}
for i := 0; i < pos; i++ {
ptr = ptr.next
}
return ptr
}
删除链表元素
// DeleteAt deletes node at given position from linked list
func (l *LinkedList) DeleteAt(pos int) error {
// validate the position
if pos < 0 {
fmt.Println("position can not be negative")
return errors.New("position can not be negative")
}
if l.len == 0 {
fmt.Println("No nodes in list")
return errors.New("No nodes in list")
}
prevNode := l.GetAt(pos - 1)
if prevNode == nil {
fmt.Println("Node not found")
return errors.New("Node not found")
}
prevNode.next = l.GetAt(pos).next
l.len--
return nil
}
// DeleteVal deletes node having given value from linked list
func (l *LinkedList) DeleteVal(val int) error {
ptr := l.head
if l.len == 0 {
fmt.Println("List is empty")
return errors.New("List is empty")
}
for i := 0; i < l.len; i++ {
if ptr.value == val {
if i > 0 {
prevNode := l.GetAt(i - 1)
prevNode.next = l.GetAt(i).next
} else {
l.head = ptr.next
}
l.len--
return nil
}
ptr = ptr.next
}
fmt.Println("Node not found")
return errors.New("Node not found")
}