go 数据结构 链表

###链表
    链表是一种物理上非顺序的一种线性的数据结构。链表由一系列节点组成,节点在运动时动态生成。每个节点包括两个部分:存储下
    个节点的指针与该节点存储的数据。
    
*链表的主要操作有
 1. func (this *ListNode) FindEleByIndex(K int) ElementType :根据位序K,返回响应元素
 2. func (this *ListNode) FindFristEleIndex(ele ElementType) int:在线性表L中查找E的第一次出现的位置
 3. func (this *ListNode) Insert(ele ElementType, i int) :在位序I前插入一个新元素E
 4. func (this *ListNode) Delete(i int) ListNode :删除指定位序I的元素
 5. func (this *ListNode) Length() int: 返回线性表L的长度  

package main

import (
	"errors"
	"fmt"
)

/**
链表的的数据单元 数据类型可以随便定义  当然可以是一些简单的基本数据类型 例如 int float string
以下是例子 我将存储一些人员信息
*/
type ElementType struct {
	Name     string //姓名
	IDNumber string //身份证号
	Sex      bool   //性别
}

type ListNode struct {
	Man      ElementType
	NextNode *ListNode
}

//获取 链表长度
func (this *ListNode) Length() int {
	i := 0
	for this != nil {
		if this != nil {
			this = this.NextNode
			i++
		}
	}
	return i

}

// 返回第 i 个元素的位置
func (this *ListNode) FindEleByIndex(K int) (ElementType, error) {
	i := 1
	for this != nil {
		if K == i {
			return this.Man, nil
		}
		i++
		this = this.NextNode
	}
	return ElementType{}, errors.New("没有该节点")

}

//在链表表 L 中查找E的第一次出现的位置
func (this *ListNode) FindFristEleIndex(ele ElementType) int {
	i := 1
	for this != nil {
		if this.Man == ele {
			return i
		}
		this = this.NextNode
		i++
	}
	return -1
}

//在第I前插入一个新元素 兼容插到最后
func (this *ListNode) Insert(ele ElementType, i int) error {
	len := this.Length()
	if i > len+1 {
		return errors.New("i应 <= " + fmt.Sprint(len+1))
	}
	j := 1
	for this != nil {
		if j+1 == i {
			newNode := ListNode{Man: ele, NextNode: this.NextNode}
			this.NextNode = &newNode
			break
		}
		this = this.NextNode
		j++
	}

	return nil
}

//删除指定位序I的元素   这种实现方案个人觉得有点不符合规范  如果各位有无返回值的实现方案 欢迎评论留言
func (this *ListNode) Delete(i int) ListNode {
	j := 1
	if i == 1 {
		this = this.NextNode
		return *this
	}
	tem := this

	for this != nil {
		if j+1 == i {
			this.NextNode = this.NextNode.NextNode
			break
		}

		this = this.NextNode
		j++
	}
	return *tem
}

//遍历
func (this *ListNode) getAll() {
	for this != nil {
		fmt.Println(this.Man)
		this = this.NextNode
	}
}
func main() {
	//var NilPoint *ListNode
	//NilPoint = nil
	list := ListNode{Man: ElementType{Name: "xiao", IDNumber: "1", Sex: true}, NextNode: nil}

	list.Insert(ElementType{Name: "liu", IDNumber: "1", Sex: true}, 2)
	list.Insert(ElementType{Name: "liu2", IDNumber: "1", Sex: true}, 3)
	fmt.Println(list.Length())

	list = list.Delete(1)
	list.getAll()
	fmt.Println(list.FindFristEleIndex(ElementType{Name: "liu2", IDNumber: "1", Sex: true}))
	fmt.Println(list.FindEleByIndex(1))

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值