19. 删除链表的倒数第 N 个结点
java
复制代码
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode slow = head;
ListNode fast = head;
//使得fast和slow之间相隔n-1个节点(fast比slow先走n步)
for(int i=0;i<n;i++){
fast=fast.next;
}
//说明删除的是头结点
if(fast==null){
return head.next;
}
//依次向后移动
while(fast.next!=null){
slow=slow.next;
fast=fast.next;
}
//将slow指向下一个节点的后继结点(不能写slow.next=fast,举例[1,2])
slow.next=slow.next.next;
//返回结果
return head;
}
}