2.5 删除链表的倒数第N个结点(线性表-链表)——【LeetCode】
作者:互联网
package com.lianbiao.java;
//19. 删除链表的倒数第 N 个结点
public class five {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode slow = dummy;
ListNode fast = dummy;
while(n >= 0) {//=号 使得fast移动了n+1步,最后保证slow指向了待删除结点的上一个结点
fast = fast.next;
n--;
}
while(fast != null) {
slow = slow.next;
fast = fast.next;
}
slow.next = slow.next.next;
return dummy.next;
}
}
class ListNode {
int val;
ListNode next;
public ListNode(int val) {
super();
this.val = val;
}
@Override
public String toString() {
return "ListNode [val=" + val + ", next=" + next + "]";
}
}
标签:dummy,slow,ListNode,线性表,val,fast,next,链表,LeetCode 来源: https://blog.csdn.net/m0_46423830/article/details/122724253