利用快慢指针来实现,快指针先执行头节点的第n个节点,慢指针指向头节点
然后快慢指针一起移动,当快指针指向尾节点时,慢指针的下一个节点就是要移除的节点
代码实现:
public class Client { public static void main(String[] args) { ListNode head = new ListNode(0); ListNode curNode = head; for (int i = 1; i < 5; i++) { ListNode nextNode = new ListNode(i); curNode.setNext(nextNode); curNode = nextNode; } removeNthFromEnd(head,3); } /** * 移除单链表的第n个节点 */ static void removeNthFromEnd(ListNode head, int n) { ListNode fast = head; ListNode slow = head; ListNode tempNode = head; for (int i = 0; i < n; i++) { fast = tempNode.getNext(); tempNode = tempNode.getNext(); } while (fast.getNext() != null){ fast=fast.getNext(); slow = slow.getNext(); } slow.setNext(slow.getNext().getNext()); } }