有时候,有这样的场景,我们需要就给定数组将其转为一个链表,通常的思路有两种:
- 正序
- 逆序
以下是具体的代码实现和测试函数:
package main
import (
"fmt"
"testing"
)
type listNode struct {
next *listNode
val int
}
// 正序遍历构建链表
// 通过一个虚拟头结点,不断向后遍历
func array2ListNode(nums []int) *listNode {
if len(nums) <= 0 {
return nil
}
var dummy = &listNode{val: 0}
var cur = dummy
for i := 0; i < len(nums); i++ {
node := &listNode{val: nums[i]}
cur.next = node
cur = cur.next
}
return dummy.next
}
// 逆序构建链表
// 每次逆序遍历时,新节点 -> head,head = newNode,以完成相关指向
func array2ListNodeInRev(nums []int) *listNode {
if len(nums) <= 0 {
return nil
}
var head *listNode
for i := len(nums) - 1; i >= 0; i-- {
node := &listNode{val: nums[i]}
node.next = head
head = node
}
return head
}
func TestArray2ListNode(t *testing.T) {
nums := []int{1, 2, 3, 4}
head := array2ListNode(nums)
for head != nil {
fmt.Printf("node: %d\n", head.val)
head = head.next
}
}
func TestArray2ListNodeInRev(t *testing.T) {
nums := []int{1, 2, 3, 4}
head := array2ListNodeInRev(nums)
for head != nil {
fmt.Printf("node: %d\n", head.val)
head = head.next
}
}
标签:node,golang,head,正序,nums,int,链表,listNode
From: https://www.cnblogs.com/davis12/p/18327392