Home > Common Problem > How to implement singly linked list in go language

How to implement singly linked list in go language

尊渡假赌尊渡假赌尊渡假赌
Release: 2023-06-09 11:50:19
Original
1539 people have browsed it

The method of implementing singly linked list in Go language is: 1. Create a Go sample file; 2. Define the linked list node structure; 3. Traverse the nodes and add new nodes at the head and tail of the linked list; 4. Specify Insert or delete a new node at the linked list position; 5. Obtain the node value at the specified position of the linked list and implement operations such as addition, deletion, modification, and query of nodes.

How to implement singly linked list in go language

Operating system for this tutorial: Windows 10 system, Go1.20.1 version, Dell G3 computer.

Singly linked lists can be implemented in Go language through structures and pointers.

The specific method is as follows:

1. Define the linked list node structure

type ListNode struct {
    Val int
    Next *ListNode
}
Copy after login

2. Implement the addition of nodes. Delete, modify, check and other operations

// 遍历节点
func (head *ListNode) Traverse() {
for head != nil {
fmt.Println(head.Val)
head = head.Next
}
}
// 在链表头添加新节点
func (head *ListNode) AddAtHead(val int) *ListNode {
node := &ListNode{
Val:  val,
Next: head,
}
return node
}
// 在链表尾添加新节点
func (head *ListNode) AddAtTail(val int) *ListNode {
if head == nil {
return &ListNode{
Val:  val,
Next: nil,
}
}
cur := head
for cur.Next != nil {
cur = cur.Next
}
cur.Next = &ListNode{
Val:  val,
Next: nil,
}
return head
}
// 在链表指定位置插入新节点
func (head *ListNode) AddAtIndex(index, val int) *ListNode {
if index <= 0 {
return head.AddAtHead(val)
}
cur := head
for i := 0; i < index-1 && cur != nil; i++ {
cur = cur.Next
}
if cur == nil {
return head
}
node := &ListNode{
Val:  val,
Next: cur.Next,
}
cur.Next = node
return head
}
// 删除链表指定位置的节点
func (head *ListNode) DeleteAtIndex(index int) *ListNode {
if index < 0 {
return head
}
if index == 0 {
return head.Next
}
cur := head
for i := 0; i < index-1 && cur != nil; i++ {
cur = cur.Next
}
if cur == nil || cur.Next == nil {
return head
}
cur.Next = cur.Next.Next
return head
}
// 获取链表指定位置的节点值
func (head *ListNode)
Copy after login

The above is the detailed content of How to implement singly linked list in go language. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template