面试题 02.02. 返回倒数第 k 个节点

实现一种算法,找出单向链表中倒数第 k 个节点。返回该节点的值。

注意:本题相对原题稍作改动

示例:

输入: 1->2->3->4->5 和 k = 2
输出: 4

说明:

给定的 k 保证是有效的。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/kth-node-from-end-of-list-lcci
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

这道题有两种方式去实现:
1,先遍历一边链表,然后依据获取到的链表节点数去处理。
2,两个点同时走的方式,让其中一个点先走k个节点,然后两个节点再同时走,当先前走了K步的节点到链表尾部的时候,后面的节点就是要找的节点。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */


int kthToLast(struct ListNode* head, int k){
    struct ListNode *preNode = head;
    struct ListNode *curNode = head;

    int i  = 0;
    while (i < k)
    {
        preNode = preNode->next;
        i += 1;
    }

    while (preNode)
    {
        preNode = preNode->next;
        curNode = curNode->next;
    }

    return curNode->val;
}
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */


int kthToLast(struct ListNode* head, int k){
    struct ListNode *curNode = head;

    int nodeNum = 0;
    while (curNode)
    {
        curNode = curNode->next;
        nodeNum += 1;
    }

    int i = 0;
    curNode = head;
    while (curNode)
    {
        if (i == nodeNum - k)
        {
            break;
        }

        i++;

        curNode = curNode->next;
    }

    return curNode->val;
}
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def kthToLast(self, head: ListNode, k: int) -> int:
        preNode = head
        curNode = head

        i = 0
        while (i < k):
            i += 1
            preNode = preNode.next

        while (preNode is not None):
            curNode = curNode.next
            preNode = preNode.next

        return curNode.val
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def kthToLast(self, head: ListNode, k: int) -> int:
        curNode = head
        nodeNum = 0
        while (curNode is not None):
            nodeNum += 1
            curNode = curNode.next
        
        curNode = head
        i = 0
        while (curNode is not None):
            if (i == nodeNum - k):
                break
            i += 1
            curNode = curNode.next

        return curNode.val

你可能感兴趣的:(leetcode,返回倒数第,k,个节点,leetcode,算法,链表,单链表)