LCR 140. 訓練計劃 II 連結串列倒數第k個節點

gdut17_2發表於2024-06-07
/**
 * 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
}

相關文章