import java.util.*; /* * public class ListNode { * int val; * ListNode next = null; * } */ public class Solution { /** * * @param head ListNode类 * @param n int整型 * @return ListNode类 */ public ListNode removeNthFromEnd (ListNode head, int n) { // write code here ListNode tmp = head; ListNode tmp2 = tmp; int num = 0; while(head != null){ num++; head = head.next; } if(num == 0){ return null; } if(n == num){ return tmp.next; } int k = 0; while(tmp != null){ if(k == num - n - 1){ tmp.next = tmp.next.next; return tmp2; }else{ k++; tmp = tmp.next; } } return tmp2; } }
两次遍历,肯定是能解决问题的。但是最优解应该是双指针。p和q,p和q相距n,当q到达末尾时p就是倒数第n个节点。