面试题 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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值