Golang is an efficient programming language whose data structures are flexible, diverse and easy to operate. In Golang, arrays and linked lists are commonly used data structures. Array is a linear structure, while linked list is a non-linear structure. In some cases, it is necessary to convert an array into a linked list to make it easier to process the data. This article will introduce how to convert an array into a linked list in Golang.
1. The difference between arrays and linked lists
Arrays and linked lists are both ways of storing a set of data, but there is a big difference between them. Here is a brief introduction to their differences:
2. Convert an array into a linked list
To convert an array into a linked list in Golang, you can use the following steps:
// Define the linked list node type
type ListNode struct {
Val int Next *ListNode
}
Here, we define a linked list node type, including nodes value and a pointer to the next node.
// Convert the array to a linked list
func arrayToList(nums []int) *ListNode {
var head *ListNode // 遍历数组 for i := len(nums) - 1; i >= 0; i-- { // 创建链表节点 node := &ListNode{nums[i], nil} node.Next = head // 将新节点链接到链表头 head = node // 将新节点设置为链表头 } return head
}
This code converts the array is a linked list. We first define a linked list head node head and initialize it to nil. Then, iterate through the array, creating each node in turn and linking it to the head of the linked list. Finally, return the head node of the linked list.
func main() {
nums := []int{1, 2, 3, 4, 5} head := arrayToList(nums) for head != nil { fmt.Print(head.Val, " ") head = head.Next }
}
We can use the above code to test the result of converting the array into a linked list. Here, we define an array [1,2,3,4,5] and convert it into a linked list. Then, by traversing the linked list, output the value of each node.
3. Summary
In Golang, converting arrays into linked lists can help us process data more conveniently. In the above method, we convert the array into a linked list by defining the linked list node type and traversing the array and linking each node to the head of the linked list. Through the above steps, we can easily convert the array into a linked list and enjoy the convenience brought by the linked list, such as convenient insertion and deletion operations.
The above is the detailed content of golang array to linked list. For more information, please follow other related articles on the PHP Chinese website!