Files
leetcode/19.remove-nth-node-from-end-of-list.java
2025-10-24 16:32:48 +08:00

52 lines
1.4 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/*
* @lc app=leetcode id=19 lang=java
*
* [19] Remove Nth Node From End of List
*/
// @lc code=start
/**
* 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 {
/**
* 在删除链表的倒数第n个node时如果想在一次遍历中删除可以使用两个指针slow fast
* 其中fast指针领先slow指针n个位置之后fast指针和slow指针以相同的pace向后移动
* 当fast到达链表尾部时slow则是倒数第n个位置
* 可以通过prev记录slow的前一个位置然后删除prev节点
*
* @param head
* @param n
* @return
*/
public ListNode removeNthFromEnd(ListNode head, int n) {
if(head == null) {
return null;
}
ListNode prev = null, slow = head, fast = head;
for(int i = 0; i < n; i++) {
fast = fast.next;
}
while(fast != null) {
fast = fast.next;
prev = slow;
slow = slow.next;
}
if(prev == null) {
head = head.next;
} else {
prev.next = slow.next;
}
return head;
}
}
// @lc code=end