検索
ホームページバックエンド開発GolangGo での単一リンクリストの実装

Hey there DEV.to community!

This is a part of my data structures and algorithms series. In this article, we will implement a singly linked list then in the next articles from this series I will implement other kinds of linked lists as well using Go.

Singly Linked List Implementation in Go

Image source: GeeksforGeeks

To implement a singly linked list we need to structures, a node and a singly linked list itself. But before beginning to code here is how I like to organize my code:


project
├── singly_linked_list
│   ├── node.go
│   └── list.go
└── main.go


Node

A node only holds data and a pointer to the next node in its simplest form. Thus here is the struct we are going to use as a node (in the node.go file):


type SinglyNode struct {
    data interface{}
    next *SinglyNode
}


We are using interface{} as the data type for data in the struct so we may store any data we want inside the node.

Then we should define some methods to utilize the node struct we've just created.


func NewSinglyNode(data interface{}) *SinglyNode {
    return &SinglyNode{data: data}
}


If you are used to object-oriented languages you are mostly likely to be familiar with what a constructor is. Since Go is not an object-oriented language there are no classes but by some conventions around the Go world, we usually create a function prefixed with the word New. But keep in mind that in the OOP languages new is a special keyword that means creating an object. Here the New is just a name prefix and nothing more.

The NewSinglyNode function receives only one argument called data with interface{} type and returns a pointer of SinglyNode.

Next, we define some getters and setters for the node:


func (n *SinglyNode) SetData(data interface{}) {
    n.data = data
}

func (n *SinglyNode) SetNext(next *SinglyNode) {
    n.next = next
}

func (n *SinglyNode) GetData() interface{} {
    return n.data
}

func (n *SinglyNode) GetNext() (*SinglyNode, error) {
    if n.next == nil {
        return nil, errors.New("no next node")
    }
    return n.next, nil
}


The SetData, Setnext and GetData are pretty much self-explanatory. The GetNext returns two values, a pointer to the next SinglyNode and an error if there is no next node.

Here is an extra function I always like to add so I can always know how the string representation of my struct is:


func (n *SinglyNode) ToString() string {
    return n.data.(string)
}


List

Now that we are done with our node we should implement the list itself. A singly linked list holds the first node as head and as for my own preference two more data called last holds the last node and a country property that holds the count of the nodes added to the list.

So here is the first lines of the list.go file:


type SinglyLinkedList struct {
    head  *SinglyNode
    last  *SinglyNode
    count int
}


And obviously, a constructor-like function to create a SinglyLinkedList with ease:


func NewSinglyLinkedList() *SinglyLinkedList {
    return &SinglyLinkedList{}
}


The most important function in a linked list is the one that adds a node. Here is my implementation of such a function:


func (l *SinglyLinkedList) AttachNode(node *SinglyNode) {
    if l.head == nil {
        l.head = node
    } else {
        l.last.SetNext(node)
    }
    l.last = node
    l.count++
}


The function does as below:

  • Check if the head of the linked list is empty, if so set the received node as the head of the list.
  • If the head is not empty it sets the received node as the next property of the last node.
  • Regardless of what happened before, the current node should be last node so the next time a node gets added it can get set as the next for the last node in our list.
  • Increase the count by one.

Here is a function that receives data and creates a node and passes it to the AttachNode function:


func (l *SinglyLinkedList) Add(data interface{}) {
    l.AttachNode(NewSinglyNode(data))
}


Although this function might seem redundant, it will ease adding nodes to the list without manually creating one each time.

A function to get the count property as well:


func (l *SinglyLinkedList) Count() int {
    return l.count
}


The last function needed is a function that should return the next node in the linked list:


func (l *SinglyLinkedList) GetNext() (*SinglyNode, error) {
    if l.head == nil {
        return nil, errors.New("list is empty")
    }
    return l.head, nil
}


I prefer to name this function as same as the GetNext function defined for the nodes. This is done so there is more consistency. When first accessing a linked list the type is a linked list so there is no access to functions defined for nodes. Defining a function with the same name will make you able to use GetNext as much as you want to traverse your list.

One extra function that I always tend to add is a function to retrieve a node by the index:


func (l *SinglyLinkedList) GetByIndex(index int) (*SinglyNode, error) {
    if l.head == nil {
        return nil, errors.New("list is empty")
    }
    if index+1 > l.count {
        return nil, errors.New("index out of range")
    }
    node, _ := l.GetNext()
    for i := 0; i 
<p>This function does as below:</p>

  • Check if the head is empty to return an error
  • Check if index+1 is greater than the count of the list to return an error. We check for index+1 and not for index since we consider the indices starting from 0 just like arrays.
  • Assign l.GetNext() to a variable named node (ignoring the error with _) then loop for one less than the index provided as we already have the first one stored in the node variable, assigning the next node of the current node as node again.
  • Return the traversed node without an error.

Testing

Now that we have our linked list and node definitions, we can test it in our main.go file just as below:


func main() {
    list := singly_linked_list.NewSinglyLinkedList()

    list.Add("One")
    list.Add("Two")
    list.Add("Three")

    firstNode, err := list.GetNext()
    if err != nil {
        panic(err)
    }

    secondNode, err := firstNode.GetNext()
    if err != nil {
        panic(err)
    }

    thirdNode, err := secondNode.GetNext()
    if err != nil {
        panic(err)
    }

    println(firstNode.ToString())  // One
    println(secondNode.ToString()) // Two
    println(thirdNode.ToString())  // Three
}


Or using the GetByIndex function:


func main() {
    list := singly_linked_list.NewSinglyLinkedList()

    list.Add("One")
    list.Add("Two")
    list.Add("Three")

    node, err := list.GetByIndex(2)
    if err != nil {
        panic(err)
    }

    fmt.Println(node.ToString()) // Three
}



BTW! Check out my free Node.js Essentials E-book here:

Feel free to contact me if you have any questions or suggestions.

以上がGo での単一リンクリストの実装の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
GOのINIT関数に依存するテストコードGOのINIT関数に依存するテストコードMay 03, 2025 am 12:20 AM

fatestinggocodewithinit functions、useexplicitsetupfunctionsurseSorseparatet fileStoavoidepencyonInitonitisideEffects.1)useexplicitsetupfuncontrollglobalbariaveInitialization.2)createSeparateSteSteSteStobypassInit funtedtententen

GOのエラー処理アプローチを他の言語と比較しますGOのエラー処理アプローチを他の言語と比較しますMay 03, 2025 am 12:20 AM

Go'serrorhandlingReturnserrorsasasvalues、javaandpython whichuseexceptions.1)go'smethodensuresexpliciterror handling

GOで効果的なインターフェイスを設計するためのベストプラクティスGOで効果的なインターフェイスを設計するためのベストプラクティスMay 03, 2025 am 12:18 AM

効果的なインターフェイスリングミニマル、クリア、およびプロモテスルーシューリング。1)インターフェイスForfforfibilityOfimplementation.2)interfacesforact forabstractiontoswapimplementations withingingcallingcode.3)設計の快適性を発信すること

GOの集中エラー処理戦略GOの集中エラー処理戦略May 03, 2025 am 12:17 AM

集中型エラー処理は、GO言語でのコードの読みやすさと保守性を向上させることができます。その実装方法と利点には、次のものが含まれます。1。ビジネスロジックからロジックを個別に処理し、コードを簡素化します。 2。中央の取り扱いによるエラー処理の一貫性を確保します。 3. DeferとRecoverを使用してパニックをキャプチャおよび処理して、プログラムの堅牢性を高めます。

GOのパッケージ初期化のINIT機能の代替案GOのパッケージ初期化のINIT機能の代替案May 03, 2025 am 12:17 AM

Ingo、AlternativestoinititionCustomInitializationAndSingletons.1)CustomInitializationAltionsionAlowoveroveroveroveroveroveroveroveroveroveroveroveroveroveroveroverover curs、beantefordedorcontionalsetups.2)singletonsensureone-initializatializatializatialent

GOインターフェイスでアサーションとタイプスイッチを入力しますGOインターフェイスでアサーションとタイプスイッチを入力しますMay 02, 2025 am 12:20 AM

gohandlesinterfacesandtypeassertionseffectivivivivivity、強化された柔軟性と耐毒性を強化します

エラーを使用し、エラーを使用して、goでエラー検査を行いますエラーを使用し、エラーを使用して、goでエラー検査を行いますMay 02, 2025 am 12:11 AM

言語エラー処理は、エラーとエラーを介してより柔軟になり、読みやすくなります。 1.エラーは、エラーが指定されたエラーと同じであり、エラーチェーンの処理に適しているかどうかを確認するために使用されます。 2.エラー。エラータイプを確認するだけでなく、エラーを特定のタイプに変換することもできます。これは、エラー情報を抽出するのに便利です。これらの関数を使用すると、エラー処理ロジックを簡素化できますが、エラーチェーンの正しい配信に注意を払い、コードの複雑さを防ぐために過度の依存性を回避できます。

GOのパフォーマンスチューニング:アプリケーションの最適化GOのパフォーマンスチューニング:アプリケーションの最適化May 02, 2025 am 12:06 AM

tomakegogoapplicationsRunfasterAndMore -efficient、useprofilingtools、leverageconconcurrency、andmanagememoryefcectively.1)useprofforcpuandmemoryprofilingtoidentififybottlenecks.2)

See all articles

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

Video Face Swap

Video Face Swap

完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

ホットツール

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強力な PHP 統合開発環境

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

このプロジェクトは osdn.net/projects/mingw に移行中です。引き続きそこでフォローしていただけます。 MinGW: GNU Compiler Collection (GCC) のネイティブ Windows ポートであり、ネイティブ Windows アプリケーションを構築するための自由に配布可能なインポート ライブラリとヘッダー ファイルであり、C99 機能をサポートする MSVC ランタイムの拡張機能が含まれています。すべての MinGW ソフトウェアは 64 ビット Windows プラットフォームで実行できます。

SublimeText3 Mac版

SublimeText3 Mac版

神レベルのコード編集ソフト(SublimeText3)

メモ帳++7.3.1

メモ帳++7.3.1

使いやすく無料のコードエディター

EditPlus 中国語クラック版

EditPlus 中国語クラック版

サイズが小さく、構文の強調表示、コード プロンプト機能はサポートされていません