52 lines
1.4 KiB
Java
52 lines
1.4 KiB
Java
/*
|
||
* @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
|
||
|