Offer-22 prove safety chain in the penultimate node k

The meaning of problems

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.

Examples

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

返回链表 4->5.

复制代码

answer

Finger bis


/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode getKthFromEnd(ListNode head, int k) {

	// 双指针法 前后指针都从head开始
        ListNode pre = head;
        ListNode end = head;

	// pre 指针走k步 此时pre与end间距长度 k
        for(int i=0;i<k;i++){
            pre = pre.next;
        }

	// pre 与 end 再同时走
	//当pre为空的时候, end所在位置正好是倒数第k位,取出即可
        while(pre != null){
            pre = pre.next;
            end = end.next;

        }
        return end;
    }
}


复制代码

Guess you like

Origin juejin.im/post/5e63ba866fb9a07cac1d6ae8