LCR 140. 训练计划 II 链表倒数第k个节点

/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func trainingPlan(head *ListNode, cnt int) *ListNode {
    
    count := 0
    p := head 
    for p!=nil {
        count++
        p=p.Next
    }

    p = head
    idx := count-cnt
    for i:=0; i<idx; i++ {
        p=p.Next
    }
    return p
}

func trainingPlan2(head *ListNode, cnt int) *ListNode {
    fast := head
    slow := head 
    for fast!=nil && cnt>0 {
        fast=fast.Next
        cnt--
    }

    for fast!=nil {
        fast=fast.Next
        slow=slow.Next
    }
    return slow
}
posted @ 2024-06-07 22:08  gdut17_2  阅读(14)  评论(0)    收藏  举报