单链表查找倒数第K个元素
给定一个单链表查找倒数第k个元素,例如单链表有节点1->2->3->4->5查找倒数第2个元素
解题思路
使用快慢指针fast和slow,fast先移动K步,slow指针指向头节点head,然后同时开始移动快慢指针指针直到fast指针移动到链表尾部时slow指针指向的节点就是倒数第k个节点元素
public class ListNode { int val; ListNode next; ListNode(int x) { val = x; } } class Solution{ public static ListNode getKthFromEnd(ListNode head,int k){ ListNode slow = head; ListNode fast = head; while(k>0){ fast = fast.next; k--; } while(fast!=null){ slow = slow.next; fast = fast.next; } return slow; } }
|
参考:
https://leetcode.cn/problems/lian-biao-zhong-dao-shu-di-kge-jie-dian-lcof/