题解 | #删除链表的倒数第n个节点#
删除链表的倒数第n个节点
http://www.nowcoder.com/practice/f95dcdafbde44b22a6d741baf71653f6
public static ListNode removeNthFromEnd (ListNode head, int n) { if (getLength(head) == n){ head = head.next; return head; } ListNode p = head, q = head; int i = 0; // 找出前后两个游标之间的距离 == n,然后连个游标不断往后移动,直到后面的游标的next为null停止 while (i < n){ q = q.next; i++; } while (q.next != null){ q = q.next; p = p.next; } p.next = p.next.next; return head; } public static int getLength(ListNode head){ int i = 0; ListNode p = head; while (p != null){ i++; p = p.next; } return i; }