快慢指针 03
0j1XlR.png
https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/
快慢指针解法
快指针先跑n个节点,如果跑到null了,说明此时慢指针就在倒数第n的位置,直接删除,即返回head的下一个元素即可。
没跑到null,则两指针一起跑,直到fast跑到null,然后通过slow删掉节点,返回head即可
/**
* 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) {
if (head == null || head.next == null) return null;
ListNode fast = head, slow = head;
for (int i = 0; i < n; i++) {
fast = fast.next;
}
if (fast == null) {
return head.next;
}
while (fast.next != null) {
fast = fast.next;
slow = slow.next;
}
slow.next = slow.next.next;
return head;
}
}
网友评论