Update the array and linked list (Go code).

This commit is contained in:
Yudong Jin 2023-01-02 18:59:35 +08:00
parent fd4737ef45
commit 1f1c58519d
3 changed files with 18 additions and 17 deletions

View File

@ -5,7 +5,6 @@
package chapter_array_and_linkedlist
import (
"fmt"
"math/rand"
)
@ -60,9 +59,10 @@ func traverse(nums []int) {
for i := 0; i < len(nums); i++ {
count++
}
count = 0
// 直接遍历数组
for index, val := range nums {
fmt.Printf("index:%v value:%v\n", index, val)
for range nums {
count++
}
}

View File

@ -9,14 +9,14 @@ import (
)
/* 在链表的结点 n0 之后插入结点 P */
func insertNode(n0 *pkg.ListNode, P *pkg.ListNode) {
func insertNode(n0 *ListNode, P *ListNode) {
n1 := n0.Next
n0.Next = P
P.Next = n1
}
/* 删除链表的结点 n0 之后的首个结点 */
func removeNode(n0 *pkg.ListNode) {
func removeNode(n0 *ListNode) {
if n0.Next == nil {
return
}
@ -27,7 +27,7 @@ func removeNode(n0 *pkg.ListNode) {
}
/* 访问链表中索引为 index 的结点 */
func access(head *pkg.ListNode, index int) *pkg.ListNode {
func access(head *ListNode, index int) *ListNode {
for i := 0; i < index; i++ {
head = head.Next
if head == nil {
@ -38,7 +38,7 @@ func access(head *pkg.ListNode, index int) *pkg.ListNode {
}
/* 在链表中查找值为 target 的首个结点 */
func findNode(head *pkg.ListNode, target int) int {
func findNode(head *ListNode, target int) int {
index := 0
for head != nil {
if head.Val == target {

View File

@ -6,18 +6,19 @@ package chapter_array_and_linkedlist
import (
"fmt"
"github.com/krahets/hello-algo/pkg"
"testing"
. "github.com/krahets/hello-algo/pkg"
)
func TestLikedList(t *testing.T) {
/* 初始化链表 1 -> 3 -> 2 -> 5 -> 4 */
// 初始化各个结点
n0 := pkg.NewListNode(1)
n1 := pkg.NewListNode(3)
n2 := pkg.NewListNode(2)
n3 := pkg.NewListNode(5)
n4 := pkg.NewListNode(4)
n0 := NewListNode(1)
n1 := NewListNode(3)
n2 := NewListNode(2)
n3 := NewListNode(5)
n4 := NewListNode(4)
// 构建引用指向
n0.Next = n1
@ -25,17 +26,17 @@ func TestLikedList(t *testing.T) {
n2.Next = n3
n3.Next = n4
fmt.Println("初始化的链表为")
pkg.PrintLinkedList(n0)
PrintLinkedList(n0)
/* 插入结点 */
insertNode(n0, pkg.NewListNode(0))
insertNode(n0, NewListNode(0))
fmt.Println("插入结点后的链表为")
pkg.PrintLinkedList(n0)
PrintLinkedList(n0)
/* 删除结点 */
removeNode(n0)
fmt.Println("删除结点后的链表为")
pkg.PrintLinkedList(n0)
PrintLinkedList(n0)
/* 访问结点 */
node := access(n0, 3)