Home Backend Development Golang How to reverse linked list in golang

How to reverse linked list in golang

Apr 23, 2023 am 10:22 AM

Reversing a linked list is a common question and is often mentioned in programming interviews. It is a classic algorithmic problem that is widely used and can be used to quickly reverse the order of a linked list. This article will introduce the algorithm and steps to implement a reverse linked list using golang language.

  1. Define a singly linked list node

Before we start to implement the reverse linked list, we need to first define a singly linked list node. A node contains two very important parts: data field and pointer field. The data field is used to store the value of the node, and the pointer field is used to point to the next node.

In golang, we can use the struct structure to define a singly linked list node. The structure contains two attributes: Val, used to represent the value of the current node, and Next, used to represent the pointer to the next node.

type ListNode struct {

Val  int
Next *ListNode
Copy after login

}

  1. Singly linked list inversion

Now we have defined the nodes of the singly linked list, The next step is to implement the algorithm for inverting the linked list. The key to reversing a linked list is to traverse the linked list and change the pointer to each node.

We can traverse each node in the linked list from the beginning, and change their "Next" pointers in turn to point to the previous node. In this way, the linked list can be reversed.

The algorithm steps for reversing the linked list are as follows:

(1) Define two pointers: pre and cur, pointing to the first node and the second node respectively. pre is the previous node and cur is the current node.

(2) Traverse the linked list and point the Next pointer of the current node to the previous node pre.

(3) Move the pointer backward, point pre to the current node, and cur to the next node.

(4) Repeat steps 2 and 3 until the entire linked list is traversed.

The implementation code is as follows:

func reverseLinkedList(head ListNode) ListNode {

var pre *ListNode
cur := head
for cur != nil {
    next := cur.Next
    cur.Next = pre
    pre = cur
    cur = next
}
return pre
Copy after login

}

  1. Reverse linked list Test code

In order to verify the correctness of the reversed linked list, we write some test code to execute.

func TestReverseLinkedList(t *testing.T) {

head := &ListNode{Val: 1}
node1 := &ListNode{Val: 2}
node2 := &ListNode{Val: 3}
node3 := &ListNode{Val: 4}
node4 := &ListNode{Val: 5}

head.Next = node1
node1.Next = node2
node2.Next = node3
node3.Next = node4

newHead := reverseLinkedList(head)

assert.Equal(t, newHead.Val, 5)
assert.Equal(t, newHead.Next.Val, 4)
assert.Equal(t, newHead.Next.Next.Val, 3)
assert.Equal(t, newHead.Next.Next.Next.Val, 2)
assert.Equal(t, newHead.Next.Next.Next.Next.Val, 1)
Copy after login

}

  1. Reverse part of the linked list

In addition to reversing the entire In addition to linked lists, we can also reverse part of the linked list. For example, reverse the part from node m to node n in the linked list. We just need to make slight modifications based on reversing the entire linked list.

We can first traverse to the m-1th node, the pre pointer points to this node, and cur points to the m-th node. Then, we perform the steps of reversing the linked list until we reverse to the nth node.

The implementation code is as follows:

func reverseBetween(head ListNode, m int, n int) ListNode {

dummy := &ListNode{0, head}
pre := dummy

for i := 1; i < m; i++ {
    pre = pre.Next
}

cur := pre.Next
for i := m; i < n; i++ {
    next := cur.Next
    cur.Next = next.Next
    next.Next = pre.Next
    pre.Next = next
}

return dummy.Next
Copy after login

}

  1. Test code for reversing partial linked list

In order to verify the correctness of reversing partial linked list, we write some test code for verification.

func TestReverseBetween(t *testing.T) {

head := &ListNode{Val: 1}
node1 := &ListNode{Val: 2}
node2 := &ListNode{Val: 3}
node3 := &ListNode{Val: 4}
node4 := &ListNode{Val: 5}

head.Next = node1
node1.Next = node2
node2.Next = node3
node3.Next = node4

newHead := reverseBetween(head, 2, 4)

assert.Equal(t, newHead.Val, 1)
assert.Equal(t, newHead.Next.Val, 4)
assert.Equal(t, newHead.Next.Next.Val, 3)
assert.Equal(t, newHead.Next.Next.Next.Val, 2)
assert.Equal(t, newHead.Next.Next.Next.Next.Val, 5)
Copy after login

}

  1. Summary

In this article, we use golang Implemented the reversal linked list algorithm, including reversing the entire linked list and reversing part of the linked list. Reversing a linked list is a common interview question and is also a basic algorithm for solving problems related to linked lists. If you are interested in linked list algorithms, it is recommended that you study in depth other linked list related algorithms, such as fast and slow pointers, circular linked lists, deleting nodes, etc.

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

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Go language pack import: What is the difference between underscore and without underscore? Go language pack import: What is the difference between underscore and without underscore? Mar 03, 2025 pm 05:17 PM

This article explains Go's package import mechanisms: named imports (e.g., import &quot;fmt&quot;) and blank imports (e.g., import _ &quot;fmt&quot;). Named imports make package contents accessible, while blank imports only execute t

How to implement short-term information transfer between pages in the Beego framework? How to implement short-term information transfer between pages in the Beego framework? Mar 03, 2025 pm 05:22 PM

This article explains Beego's NewFlash() function for inter-page data transfer in web applications. It focuses on using NewFlash() to display temporary messages (success, error, warning) between controllers, leveraging the session mechanism. Limita

How to convert MySQL query result List into a custom structure slice in Go language? How to convert MySQL query result List into a custom structure slice in Go language? Mar 03, 2025 pm 05:18 PM

This article details efficient conversion of MySQL query results into Go struct slices. It emphasizes using database/sql's Scan method for optimal performance, avoiding manual parsing. Best practices for struct field mapping using db tags and robus

How can I define custom type constraints for generics in Go? How can I define custom type constraints for generics in Go? Mar 10, 2025 pm 03:20 PM

This article explores Go's custom type constraints for generics. It details how interfaces define minimum type requirements for generic functions, improving type safety and code reusability. The article also discusses limitations and best practices

How do I write mock objects and stubs for testing in Go? How do I write mock objects and stubs for testing in Go? Mar 10, 2025 pm 05:38 PM

This article demonstrates creating mocks and stubs in Go for unit testing. It emphasizes using interfaces, provides examples of mock implementations, and discusses best practices like keeping mocks focused and using assertion libraries. The articl

How to write files in Go language conveniently? How to write files in Go language conveniently? Mar 03, 2025 pm 05:15 PM

This article details efficient file writing in Go, comparing os.WriteFile (suitable for small files) with os.OpenFile and buffered writes (optimal for large files). It emphasizes robust error handling, using defer, and checking for specific errors.

How do you write unit tests in Go? How do you write unit tests in Go? Mar 21, 2025 pm 06:34 PM

The article discusses writing unit tests in Go, covering best practices, mocking techniques, and tools for efficient test management.

How can I use tracing tools to understand the execution flow of my Go applications? How can I use tracing tools to understand the execution flow of my Go applications? Mar 10, 2025 pm 05:36 PM

This article explores using tracing tools to analyze Go application execution flow. It discusses manual and automatic instrumentation techniques, comparing tools like Jaeger, Zipkin, and OpenTelemetry, and highlighting effective data visualization

See all articles