描述
给定一个链表,删除链表的倒数第 n 个节点并返回链表的头指针
例如,
给出的链表为: 1→2→3→4→5, n=2.
删除了链表的倒数第 n 个节点之后,链表变为1→2→3→5
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类
* @param n int整型
* @return ListNode类
*/
public ListNode removeNthFromEnd (ListNode head, int n) {
// write code here
//三个指针
ListNode dummy = new ListNode(-1);
ListNode pre = dummy;
pre.next = head;
ListNode slow = head,fast = head;
for(int i = 1;i<n;i++){
fast = fast.next;
}
while(fast.next!=null){
//三指针同时移动
pre = pre.next;
slow = slow.next;
fast = fast.next;
}
//如果三个指针未移动
if(pre.next==head){
return head.next;
}
pre.next = slow.next;
return dummy.next;
}
}