首页 > 其他分享 >Go - Creating Linked Lists

Go - Creating Linked Lists

时间:2023-10-09 09:56:04浏览次数:27  
标签:head Creating list Lists next current Go element linked

Problem: You want to create a linked list data structure.


Solution: Create an element struct that has a pointer to the next element. Wrap another struct around the first element to create a linked list.

 

A linked list is a linear collection of elements that has each element pointing to the next element. This is different from a list because in lists the elements are next to each other (incrementing the index of the current element will give you access to the next element) while for a linked list this is not necessarily so. As a result, inserting or removing an element is faster because you don’t need to restructure the data structure, unlike in a list. On the other hand, accessing random elements in a linked list is slower because elements are not indexed, so you need to iterate through the elements until the correct one is found.

The functions for the singly linked list are:
Add
• Add a new element to the end of the linked list.
Insert
• Insert a new element into a specific position within the linked list.
Delete
• Remove a specific element from the linked list.
Find
• Find and return an element from the linked list.

In a linked list, you will use two structs — one to represent the data structure, LinkedList , and another to represent an element in the data structure, Element :

import   "golang.org/x/exp/constraints" 

type   Element [ T   constraints . Ordered ]   struct   { 
      value   T 
      next    * Element [ T ] 
} 

type   LinkedList [ T   constraints . Ordered ]   struct   { 
      head   * Element [ T ] 
      size   int 
}

You need to do this because each element in the linked list points to the next; therefore it needs to keep a pointer to the next. You create an Element struct to represent an element, with a next field pointing to the next element. The Element struct also has a value, which is of type T , constrained by the constraints.Ordered type. This means you can use the ordering operators (<, >, <=, >=) on Element values.

You create a LinkedList struct to keep track of the head of the linked list and its size. You need this struct to associate all the linked list functions.

func   ( l   * LinkedList [ T ])   Add ( el   * Element [ T ])   { 
      if   l . head   ==   nil   { 
          l . head   =   el 
      }   else   { 
          el . next   =   l . head 
          l . head   =   el 
      } 
      l . size ++ 
}

func   ( l   * LinkedList [ T ])   Insert ( el   * Element [ T ],   marker   T )   error   { 
      for   current   :=   l . head ;   current . next   !=   nil ;   current   =   current . next   { 
          if   current . value   ==   marker   { 
              el . next   =   current . next 
              current . next   =   el 
              l . size ++ 
              return   nil 
          } 
      } 
      return   errors . New ( "element  not  found" ) 
}

func   ( l   * LinkedList [ T ])   Delete ( el   * Element [ T ])   error   { 
      prev   :=   l . head 
      current   :=   l . head 
      for   current   !=   nil   { 
          if   current . value   ==   el . value   { 
              if   current   ==   l . head   { 
                  l . head   =   current . next 
              }   else   { 
                  prev . next   =   current . next 
              } 
              l . size - - 
              return   nil 
          } 
          prev   =   current 
          current   =   current . next 
      } 
      return   errors . New ( "element  not  found" ) 

}

func   ( l   * LinkedList [ T ])   Find ( value   T )   ( el   * Element [ T ],   err   error )   { 
      for   current   :=   l . head ;   current . next   !=   nil ;   current   =   current . next   { 
          if   current . value   ==   value   { 
              el   =   current 
              break 
          } 
      } 
      if   el   ==   nil   { 
          err   =   errors . New ( "element  not  found" ) 
      } 
      return 
}

func   ( l   * LinkedList [ T ])   List ()   ( list   [] * Element [ T ])   { 
      if   l . head   ==   nil   { 
          return   [] * Element [ T ]{} 
      } 
      for   current   :=   l . head ;   current   !=   nil ;   current   =   current . next   { 
          list   =   append ( list ,   current ) 
      } 
      return 
}

func   ( l   * LinkedList [ T ])   IsEmpty ()   bool   { 
      return   l . size   ==   0 
} 

func   ( l   * LinkedList [ T ])   Size ()   int   { 
      return   l . size 
}

The standard library has a container package with a few data structure implementations, and it includes a doubly linked list. If you’re looking for a linked list, this would be a good place to start.

 

标签:head,Creating,list,Lists,next,current,Go,element,linked
From: https://www.cnblogs.com/zhangzhihui/p/17750792.html

相关文章

  • 【最佳实践】MongoDB导出导入数据
    首先说一下这个3节点MongoDB集群各个维度的数据规模:1、dataSize:1.9T2、storageSize:600G3、全量备份-加压缩开关:186G,耗时8h4、全量备份-不加压缩开关:1.8T,耗时4h27m具体导出的语法比较简单,此处不再赘述,本文重点描述导入的优化过程,最后给出导入的最佳实践。■2023-09-13......
  • Go 复合类型之切片类型介绍
    Go复合类型之切片类型目录Go复合类型之切片类型一、引入二、切片(Slice)概述2.1基本介绍2.2特点2.3切片与数组的区别三、切片声明与初始化3.1方式一:使用切片字面量初始化3.2方式二:使用make函数初始化3.3方式三:基于数组的切片化四、切片的本质(底层实现原理)五、切片的动......
  • Go 语言代码简单的在线购物平台:
    以下是一个相对复杂的Go语言代码示例,用于实现一个简单的在线购物平台:packagemainimport( "fmt")typeUserstruct{ IDint Namestring Emailstring Passwordstring Addressstring}typeProductstruct{ IDint Namestring Priceflo......
  • 【最佳实践】MongoDB导入数据时重建索引
    MongoDB一个广为诟病的问题是,大量数据resotore时索引重建非常缓慢,实测5000万的集合如果有3个以上的索引需要恢复,几乎没法成功,而且resotore时如果选择创建索引也会存在索引不生效的问题,种种情况表明,MongoDB的一些默认设置存在明显不合理之处。当然,深入理解后总会有办法解决这些问......
  • golang 使用gomail.v2发送电子邮件
    1packageemail23import(4"errors"5"gopkg.in/gomail.v2"6)78vardialer*gomail.Dialer910funcReset(hoststring,portint,username,passwordstring){11dialer=gomail.NewDialer(host,port,usern......
  • Unity 通信方案 - 使用 Google Protobuf 序列化数据
    1.下载和编译1.1下载ProtoBuf源文件从github下载最新的protoBuf库,如下图所示 Releases·protocolbuffers/protobuf(github.com)1.2编译dll和导入解压后打开/scharp/src中的sln工程文件 选择Release,Google.Protobuf,之后在生成中生成文件在......
  • Django发送邮件
    Django发送邮件在Python中已经内置了一个smtp邮件发送模块,Django在此基础上进行了简单地封装。首先,我们需要在项目的settings文件中配置邮件发送参数,分别如下#使用本地文件作为邮件后端EMAIL_BACKEND='django.core.mail.backends.smtp.EmailBackend'##使用控制台作为......
  • Go - Creating Sets
    Problem: Youwanttocreateasetdatastructure.Solution: Wrapastructaroundamap.Createsetfunctionsonthestruct. Asetisanunordereddatastructurethathasonlyuniqueelements.Itimplementsthemathematicalconceptofafinitesetandt......
  • Go - Creating Stacks
    Problem: Youwanttocreateastackdatastructure.Solution: Wrapastructaroundaslice.Createstackfunctionsonthestruct. Astackisalast-in-first-out(LIFO)orderedlist.Youaddelementsatthetopofthestackandgetelementsfromt......
  • Go - Creating Queues
    Problem: Youwanttocreateaqueuedatastructure.Solution: Wrapastructaroundaslice.Createqueuefunctionsonthestruct. Aqueueisafirst-in-first-out(FIFO)orderedlist.Youaddelementsatthebackofthequeueandgetelementsatt......