Prove safety Offer - face questions linked list 22. The penultimate node k (speed pointer)

1. Topic

Input a linked list, the linked list output penultimate node k. In order to meet the habit of most people, this question counted from 1, that is the end of the list of nodes is the penultimate one node. For example, a linked list has six nodes, the nodes start from scratch, their values ​​are sequentially 1,2,3,4,5,6. The list of nodes is the reciprocal value of the third node 4.

示例:
给定一个链表: 1->2->3->4->5, 和 k = 2.
返回链表 4->5.

Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/lian-biao-zhong-dao-shu-di-kge-jie-dian-lcof
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.

2. Problem Solving

  • Go fast pointer k steps
  • Subsequently speed pointer is advanced together until the pointer reaches fast NULL
  • Slow pointer to the penultimate node k
class Solution {
public:
    ListNode* getKthFromEnd(ListNode* head, int k) {
        ListNode *fast = head, *slow = head;
        while(k--)
        	fast = fast->next;
        while(fast)
        {
        	fast = fast->next;
        	slow = slow->next;
        }
        return slow;
    }
};

Here Insert Picture Description

Published 641 original articles · won praise 494 · Views 140,000 +

Guess you like

Origin blog.csdn.net/qq_21201267/article/details/104318179