1.创建虚拟头结点ListNode pre=new ListNode(0,head);
2.创建快慢节点
3.快节点fastIndex先往后移N个位置
4.快慢slowIndex节点一直往后移,直至快节点到链表末尾
5.删除慢节点后面的节点
1 class Solution { 2 public ListNode removeNthFromEnd(ListNode head, int n) { 3 ListNode pre=new ListNode(0,head); 4 ListNode fastIndex=pre; 5 ListNode slowIndex=pre; 6 for(int i=0;i<n;i++){ 7 fastIndex=fastIndex.next; 8 } 9 while(fastIndex.next!=null){ 10 fastIndex=fastIndex.next; 11 slowIndex=slowIndex.next; 12 } 13 if(slowIndex.next!=null){ 14 slowIndex.next=slowIndex.next.next; 15 } 16 return pre.next; 17 18 } 19 }
标签:pre,Q20,head,ListNode,int,链表,LeetCode19,节点 From: https://www.cnblogs.com/cff1/p/18240136