用双指针可以解决
public class Solution { public ListNode getKthFromEnd(ListNode head, int k) { ListNode temp = head; while(temp!=null){ if(k<=0){ head = head.next; } temp = temp.next; k--; } return head; } }
普通遍历
class Solution { public ListNode getKthFromEnd(ListNode head, int k) { ListNode temp = head; ArrayList<ListNode>al = new ArrayList<ListNode>(); while(temp!=null){ al.add(temp); temp = temp.next; } return al.get(al.size()-k); } }