class Solution { public ListNode getKthFromEnd(ListNode head, int k) { ListNode p = head; int count = 0; while(p!=null){ count++; p = p.next; } if(k>count) return null; int m = count - k ; while(m>0){ head = head.next; m--; } return head; } }
先确定结点总数,再遍历。
方法二:
一次遍历,两个指针
class Solution { public ListNode getKthFromEnd(ListNode head, int k) { if(head == null || k == 0) return null; ListNode p = head; ListNode q = head; while (p!=null){ while(k>0){ if(p == null) return null; p = p.next; k--; } if(p != null) { p = p.next; q = q.next; } } return q; } }