golang获取链表倒数第k个元素

获取链表倒数第k个元素

Posted by 果果 on December 6, 2022

golang获取链表倒数第k个元素

package main

import (
	"errors"
	"fmt"
)

type NodeList struct {
	Val  int
	Next *NodeList
}

func initNodeList(k int) *NodeList {
	head := &NodeList{
		Val: 1,
	}

	for i := 2; i <= k; i++ {
		node := &NodeList{
			Val: i,
		}
		head.Next = node
		head = node
	}

	return head
}

func GetList(head *NodeList, k int) (*NodeList, error) {
	aP := head
	bP := head
	for i := 0; i < k; i++ {
		aP = aP.Next
		// 到达链表尾结点,表明 k 大于链表长度
		if aP == nil {
			return nil, errors.New("k超过链表最大长度")
		}
	}
	
	for aP != nil {
		bP = bP.Next
		aP = aP.Next
    }

	return bP, nil
}

func main() {
	nodeList := initNodeList(5)
	list, _ := GetList(nodeList, 2)
	fmt.Println(list) // &{4 0xc0000142a0}
}