牛客题霸NC53删除链表的倒数第n个节点Java题解
牛客题霸NC53删除链表的倒数第n个节点Java题解
方法:快慢指针
解题思路:利用快慢指针,让快指针former先走n步,然后再让快指针former和慢指针latter一起走,这样当快指针指向链表的末尾为null时,慢指针刚好指向链表的倒数第n个节点。再将第n个节点删除即可。这里利用了一个pre指针保存latter的前驱节点,便于删除操作。
import java.util.*; /* * public class ListNode { * int val; * ListNode next = null; * } */ public class Solution { /** * * @param head ListNode类 * @param n int整型 * @return ListNode类 */ public ListNode removeNthFromEnd (ListNode head, int n) { if(head == null || n<=0){ return null; } ListNode former = head; ListNode latter = head; ListNode pre = null; //latter的前驱 //former先走n步 for(int i=0;i<n;i++){ if(former == null){ //n大于链表长度时 return null; } former = former.next; } //former和latter一起走 while(former!=null){ former = former.next; pre = latter; latter = latter.next; } //latter就是倒数第n个节点 //删除latter节点 if(pre!=null){ pre.next = latter.next; }else{ //当pre==null时,删除头节点 例如:{1},1 head = head.next; } return head; } }