• golang go语言 实现链表


    package main
    
    import (
    	"errors"
    	"fmt"
    	"strconv"
    )
    
    type List struct {
    	Length int
    	Head  *Node
    }
    
    type Node struct {
    	NextNode *Node
    	Value int
    }
    
    func (list *List) IsEmpty() bool {
    	return list.Length == 0
    }
    
    func (list *List) Append(value int) {
    	list.Length += 1
    	if list.Head == nil {
    		list.Head = &Node{Value: value}
    		return
    	}
    	lastNode := list.Head
    	for lastNode.NextNode != nil {
    		lastNode = lastNode.NextNode
    	}
    	lastNode.NextNode = &Node{Value: value}
    }
    
    func (list *List) Delete(index int) error {
    	if index + 1 > list.Length {
    		return errors.New("index out of range")
    	}
    	list.Length -= 1
    	if index == 0{
    		list.Head = list.Head.NextNode
    		return nil
    	}
    	indexNode := list.Head
    	for i := index; i > 1; i-- {
    		indexNode = indexNode.NextNode
    	}
    	if indexNode.NextNode != nil {
    		indexNode.NextNode = indexNode.NextNode.NextNode
    	} else {
    		indexNode.NextNode = nil
    	}
    	return nil
    }
    
    func (list *List) String() string {
    	var ret string
    	node := list.Head
    	for node.NextNode != nil {
    		ret += strconv.Itoa(node.Value) + ","
    		node = node.NextNode
    	}
    	ret += strconv.Itoa(node.Value)
    	return ret
    }
    
    func (list *List) Insert(index, value int) error {
    	if index + 1 > list.Length {
    		return errors.New("index out of range")
    	}
    	list.Length++
    	if index == 0{
    		list.Head = &Node{Value:value, NextNode:list.Head}
    		return nil
    	}
    	indexNode := list.Head
    	for i := index; i > 1; i-- {
    		indexNode = indexNode.NextNode
    	}
    	tempNode := &Node{Value: value, NextNode: indexNode.NextNode}
    	indexNode.NextNode = tempNode
    	return nil
    }
    
    
    func main() {
    	a := List{}
    	for i := 0; i < 10; i++ {
    		a.Append(i)
    	}
    	fmt.Println(a.String())
    	if err := a.Insert(9, 99); err != nil{
    		fmt.Println(err)
    	}
    	fmt.Println(a.String())
    }
    

      

  • 相关阅读:
    C语言中do...while(0)用法小结
    C语言函数指针的用法
    C语言预处理命令之条件编译
    欧拉计划11-15题
    欧拉计划6-10题
    已加载“C:WindowsSysWOW64 tdll.dll”。无法查找或打开 PDB 文件。
    C++使用SQLite步骤及示例
    linux 安装sysstat使用iostat、mpstat、sar、sa
    Nmon命令行:Linux系统性能的监测利器
    linux服务器性能检测工具nmon使用
  • 原文地址:https://www.cnblogs.com/shenwenlong/p/11721535.html
Copyright © 2020-2023  润新知