给定一个链表,删除链表中倒数第n个节点,返回链表的头节点。
/**
* Definition for ListNode.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int val) {
* this.val = val;
* this.next = null;
* }
* }
*/
public class Solution {
/*
* @param head: The first node of linked list.
* @param n: An integer
* @return: The head of linked list.
*/
public ListNode removeNthFromEnd(ListNode head, int n) {
// write your code here
if (head == null)
return null;
ListNode newHead = new ListNode(-1);
newHead.next = head;
ListNode quicker = head;
ListNode slower = newHead;
while (n-- > 0)
quicker = quicker.next;
while (quicker != null) {
slower = slower.next;
quicker = quicker.next;
}
slower.next = slower.next.next;
return newHead.next;
}
}