链表中倒数最后k个节点

2022-03-31 14:24:22 浏览数 (1)

链表中倒数最后k个节点

22.链表中倒数最后k个节点
描述
代码语言:javascript复制
思路:1.快慢指针 2.存入容器vector<*ListNode*>,取倒数k个节点(v.size-k)
代码语言:javascript复制
/**
 * struct ListNode {
 *    int val;
 *    struct ListNode *next;
 *    ListNode(int x) : val(x), next(nullptr) {}
 * };
 */
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param pHead ListNode类 
     * @param k int整型 
     * @return ListNode类
     */
    ListNode* FindKthToTail(ListNode* pHead, int k) {
        // write code here
        if (!pHead) {
            return pHead;
        }
        ListNode *fast = pHead;
        ListNode *slow = pHead;
        while (k--) {
            if (!fast) {
                return NULL;
            }
            fast = fast->next;
        }
        while (fast) {
            fast = fast->next;
            slow = slow->next;
        }
        return slow;
    }
};
代码语言:javascript复制
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 
# @param pHead ListNode类 
# @param k int整型 
# @return ListNode类
#
class Solution:
    def FindKthToTail(self , pHead: ListNode, k: int) -> ListNode:
        # write code here
        if not pHead:return pHead
        if k <= 0:
            return None
        fast = pHead
        slow = pHead
        for i in range(k):
            if not fast:return None
            fast = fast.next
        while fast:
            fast = fast.next
            slow = slow.next
        return slow

0 人点赞