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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

What are the vulnerabilities of Debian OpenSSL What are the vulnerabilities of Debian OpenSSL Apr 02, 2025 am 07:30 AM

OpenSSL, as an open source library widely used in secure communications, provides encryption algorithms, keys and certificate management functions. However, there are some known security vulnerabilities in its historical version, some of which are extremely harmful. This article will focus on common vulnerabilities and response measures for OpenSSL in Debian systems. DebianOpenSSL known vulnerabilities: OpenSSL has experienced several serious vulnerabilities, such as: Heart Bleeding Vulnerability (CVE-2014-0160): This vulnerability affects OpenSSL 1.0.1 to 1.0.1f and 1.0.2 to 1.0.2 beta versions. An attacker can use this vulnerability to unauthorized read sensitive information on the server, including encryption keys, etc.

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 do you use the pprof tool to analyze Go performance? How do you use the pprof tool to analyze Go performance? Mar 21, 2025 pm 06:37 PM

The article explains how to use the pprof tool for analyzing Go performance, including enabling profiling, collecting data, and identifying common bottlenecks like CPU and memory issues.Character count: 159

What libraries are used for floating point number operations in Go? What libraries are used for floating point number operations in Go? Apr 02, 2025 pm 02:06 PM

The library used for floating-point number operation in Go language introduces how to ensure the accuracy is...

What is the problem with Queue thread in Go's crawler Colly? What is the problem with Queue thread in Go's crawler Colly? Apr 02, 2025 pm 02:09 PM

Queue threading problem in Go crawler Colly explores the problem of using the Colly crawler library in Go language, developers often encounter problems with threads and request queues. �...

PostgreSQL monitoring method under Debian PostgreSQL monitoring method under Debian Apr 02, 2025 am 07:27 AM

This article introduces a variety of methods and tools to monitor PostgreSQL databases under the Debian system, helping you to fully grasp database performance monitoring. 1. Use PostgreSQL to build-in monitoring view PostgreSQL itself provides multiple views for monitoring database activities: pg_stat_activity: displays database activities in real time, including connections, queries, transactions and other information. pg_stat_replication: Monitors replication status, especially suitable for stream replication clusters. pg_stat_database: Provides database statistics, such as database size, transaction commit/rollback times and other key indicators. 2. Use log analysis tool pgBadg

Transforming from front-end to back-end development, is it more promising to learn Java or Golang? Transforming from front-end to back-end development, is it more promising to learn Java or Golang? Apr 02, 2025 am 09:12 AM

Backend learning path: The exploration journey from front-end to back-end As a back-end beginner who transforms from front-end development, you already have the foundation of nodejs,...

How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? Apr 02, 2025 pm 04:54 PM

The problem of using RedisStream to implement message queues in Go language is using Go language and Redis...

See all articles