时间击败100%用户的快慢指针删除链表中的倒数第n个节点算法

//给你一个链表,删除链表的倒数第 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) { int i = 1; ListNode fast = head; ListNode slow = head; while(fast.next!=null){ fast = fast.next; if(i>n){ slow = slow.next; } i++; } if(i==n){ return head.next; }else{ slow.next = slow.next.next; return head; } } }

 

//快指针移动到i>n时,慢指针开始移动,最后慢指针指向待删除节点的前一个节点

posted @ 2023-02-26 10:24  Zzzzzzxz  阅读(26)  评论(0)    收藏  举报