《LeetCode力扣练习》代码随想录——链表(删除链表的倒数第N个节点---Java)
《LeetCode力扣练习》代码随想录——链表(删除链表的倒数第N个节点—Java)
刷题思路来源于 代码随想录
19. 删除链表的倒数第 N 个结点
-
双指针
/** * 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.next==null&&n==1){ return null; } ListNode dummyHead=new ListNode(-1,head); ListNode slow=dummyHead; ListNode fast=dummyHead; n++; while(n>0){ fast=fast.next; n--; } while(fast!=null){ slow=slow.next; fast=fast.next; } slow.next=slow.next.next; return dummyHead.next; } }