leetcode:https://leetcode-cn.com/problemset/lcof

数据结构

--数组

--链表

21

22链表中倒数第k个节点

class Solution {
    public ListNode getKthFromEnd(ListNode head, int k) {
        if(head == null && head.next ==null){
            return head;
        }
        //定义p、q指针指向head,p先向前走k步,接着p、q同时向前走,
        //当p指向null时,q指向的节点即为链表的倒数第k个节点。   
        ListNode p =head,q =head;
        while(k-- > 0){
            p = p.next;
        }
        while(p!=null){
            p =p.next;
            q =q.next;
        }
        return q;
    }
}
View Code

相关文章: