面试题 02.02. Kth Node From End of List LCCI

Problem

Implement an algorithm to find the kth to last element of a singly linked list. Return the value of the element.

Note:

  • k is always valid.
  • This problem is slightly different from the original one in the book.

Example

Input: 1->2->3->4->5 和 k = 2
Output: 4

Solution

经典的双指针。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    int kthToLast(ListNode* head, int k) {
        ListNode* fast = head;
        ListNode* slow = head;

        while(k > 0 && fast)
        {
            fast = fast->next;
            --k;
        }

        while(fast)
        {
            fast = fast->next;
            slow = slow->next;
        }

        return slow->val;

    }
};
发布了526 篇原创文章 · 获赞 215 · 访问量 54万+

猜你喜欢

转载自blog.csdn.net/sjt091110317/article/details/105060198