How to reverse linked list in golang
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.
- 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
}
- 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
}
- 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)
}
- 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
}
- 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)
}
- 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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

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

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

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

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

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

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.

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

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
