思路是:先取一个指针,让这个指针到达第n个节点,然后在取一个节点指向头节点,两个指针同时向后移动,直到第一个指针指向尾节点,此时第二个指针指向的节点就是要删 除的节点的前一个节点。
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { public ListNode removeNthFromEnd(ListNode head, int n) { if(head == null || head.next == null) return null; ListNode p = head, q = head; while(n != 0) { p = p.next; n--; } if(p == null) return head.next; while(p.next != null) { q = q.next; p = p.next; } q.next = q.next.next; return head; } }