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

相关文章:

  • 2021-05-07
  • 2021-05-22
  • 2021-07-21
  • 2021-11-10
  • 2021-08-29
猜你喜欢
  • 2021-06-02
  • 2022-12-23
  • 2021-08-07
  • 2022-12-23
  • 2021-12-01
  • 2021-07-13
  • 2021-09-30
相关资源
相似解决方案