- 题目描述
-
思路
1、先遍历一遍链表求链表长度,然后减去K值,再从头遍历到差值即可
2、使用快慢指针也行 -
代码:
func getKthFromEnd(head *ListNode, k int) *ListNode {
var len , root = 0, head
for {
if root == nil{
break
}
len ++
root = root.Next
}
for i:=0; i<len-k; i++ {
head = head.Next
}
return head
}
测试代码:
package main
import "fmt"
type ListNode struct {
Val int
Next *ListNode
}
func main() {
//创建链表
list := []int{1,2,3,4,5}
root := &ListNode{Val:list[0]}
tail := root
for i:=1;i<len(list);i++ {
tail.Next = &ListNode{Val:list[i]}
tail = tail.Next
}
//执行程序
root = getKthFromEnd(root,2)
//输出结果
for {
if root == nil{
break
}
fmt.Println(root.Val)
root = root.Next
}
}
func getKthFromEnd(head *ListNode, k int) *ListNode {
var len , root = 0, head
for {
if root == nil{
break
}
len ++
root = root.Next
}
for i:=0; i<len-k; i++ {
head = head.Next
}
return head
}