随笔-删除倒数第n个结点

版权声明:中华人民共和国持有版权 https://blog.csdn.net/Fly_Fly_Zhang/article/details/84919553

问题:链表删除倒数第n个结点:

思路:设置快慢指针,当fast走到链表尾部,slow所在的位置正好是要删除结点的上一个; 这样比得到长度,然后再去遍历时间复杂度低很多。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
         ListNode fast = head, slow = head;
        while (n > 0) {
            fast = fast.next;
            n--;
        }
        if (fast == null)  //删除头结点
            return slow.next;
        while (fast.next != null) {
            fast = fast.next;
            slow = slow.next;
        }
        slow.next = slow.next.next;
        return head;
    }
}

猜你喜欢

转载自blog.csdn.net/Fly_Fly_Zhang/article/details/84919553