doc: 2025-10-24打卡

This commit is contained in:
wu xiangkai
2025-10-24 16:32:48 +08:00
parent 0540e83113
commit 6dc597fa75
5 changed files with 227 additions and 0 deletions

View File

@@ -0,0 +1,51 @@
/*
* @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