go 链表反

栏目: Go · 发布时间: 7年前

链表操作是数据结构中基本的操作,下面用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

}


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

About Face 3

About Face 3

Alan Cooper、Robert Reimann、David Cronin / John Wiley & Sons / 2007-5-15 / GBP 28.99

* The return of the authoritative bestseller includes all new content relevant to the popularization of how About Face maintains its relevance to new Web technologies such as AJAX and mobile platforms......一起来看看 《About Face 3》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

随机密码生成器
随机密码生成器

多种字符组合密码

SHA 加密
SHA 加密

SHA 加密工具