2022-5-8 链表
给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode() {} 7 * ListNode(int val) { this.val = val; } 8 * ListNode(int val, ListNode next) { this.val = val; this.next = next; } 9 * } 10 */ 11 class Solution { 12 public ListNode removeNthFromEnd(ListNode head, int n) { 13 ListNode fast=head,slow=head; 14 for (int i=0;i<n;i++){ 15 fast=fast.next; 16 } 17 ListNode prev=null; 18 while (fast!=null){ 19 fast=fast.next; 20 prev=slow; 21 slow=slow.next; 22 } 23 if (prev==null) return head.next; 24 prev.next=slow.next; 25 return head; 26 } 27 }
思路:快慢指针。
浙公网安备 33010602011771号