题解 | #删除链表的倒数第n个节点#
删除链表的倒数第n个节点
https://www.nowcoder.com/practice/f95dcdafbde44b22a6d741baf71653f6
* 可以在找倒数第n个节点的基础上进行修改。
* 单链表中,删除一个节点需要知道其前一个节点,因此要删除倒数第n个节点,就要找到倒数第n+1个节点,之后将倒数第n+1个节点的next指向倒数第n-1个节点。
```java
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* }
*/
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);
dummy.next = head;
ListNode slow = dummy;
ListNode fast = dummy;
int count = 0;
while(fast != null){
if(count < (n+1)){
// System.out.println(fast.val);
fast = fast.next;
count++;
continue;
} else{
slow = slow.next;
fast = fast.next;
}
}
// System.out.println(slow.val);
if(slow.next != null){
slow.next = slow.next.next;
}
return dummy.next;
}
}
/*
* public class ListNode {
* int val;
* ListNode next = null;
* }
*/
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);
dummy.next = head;
ListNode slow = dummy;
ListNode fast = dummy;
int count = 0;
while(fast != null){
if(count < (n+1)){
// System.out.println(fast.val);
fast = fast.next;
count++;
continue;
} else{
slow = slow.next;
fast = fast.next;
}
}
// System.out.println(slow.val);
if(slow.next != null){
slow.next = slow.next.next;
}
return dummy.next;
}
}
```