链表操作是数据结构中基本的操作,下面用golang实现一下链表的基本操作,包括增、删、查以及单链表的反转操作。
package link
import (
"fmt"
"github.com/pkg/errors"
)
//链表结构
type ListNode struct {
data int
next *ListNode
}
//初始化链表头,下面的所有操作都是基于带头链表
func NewListNode() *ListNode {
return &ListNode{next: nil}
}
//获取链表的长度
func (l *ListNode)Length() int {
len :=0
for l.next != nil {
len++
l = l.next
}
return len
}
//插入节点
func (l *ListNode)InsertNode(d int) error {
newNode :=new(ListNode)
newNode.data = d
newNode.next = l.next
l.next = newNode
return nil
}
//删除节点
func (l *ListNode)DelNode(d int) {
if l == nil {
errors.New("Empty List!")
return
}
for l.next != nil {
if l.next.data == d {
l.next = l.next.next
//return 此处控制找到相同数据是否全部删除操作
}
l = l.next
}
}
//遍历链表
func (l *ListNode)ListNode() {
for l.next != nil {
fmt.Printf(" %d", l.next.data)
l = l.next
}
}
//获取链表第一个元素
func (l *ListNode)GetFirstNode() *ListNode {
return l.next
}
//递归单链反转
func ReverseList(pHead, node *ListNode) *ListNode {
if node.next == nil {
pHead.next = node
return node
}
n := ReverseList(pHead, node.next)
if n != nil {
n.next = node
node.next = nil
}
return node
}
//遍历单链反转方法
func (pHead *ListNode)ReverseListV2() {
pReversedHead := pHead
var pNode = pHead.next
var pPrev *ListNode
for pNode != nil {
pNext := pNode.next
if pNext == nil {
pReversedHead.next = pNode
}
pNode.next = pPrev
pPrev = pNode
pNode = pNext
}
return
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Automate This
Christopher Steiner / Portfolio / 2013-8-9 / USD 25.95
"The rousing story of the last gasp of human agency and how today's best and brightest minds are endeavoring to put an end to it." It used to be that to diagnose an illness, interpret legal docume......一起来看看 《Automate This》 这本书的介绍吧!