[LeetCode][链表]remove nth node from end of list java

    xiaoxiao2022-07-07  142

    1.题目:

    Given a linked list, remove the n th node from the end of list and return its head.

    For example,

    Given linked list: 1->2->3->4->5, and n = 2. After removing the second node from the end, the linked list becomes 1->2->3->5.

    Note:  Given n will always be valid. Try to do this in one pass.

     

    2.思路:

    本来没思路,但是搜了一下,大家都用的经典的快慢指针,先拿一个fast指针,先走n步,然后在fast和slow一起走,然后在fast==null的时候slow.next所指向的指针给删掉

    3.代码:

    /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { public ListNode removeNthFromEnd(ListNode head, int n) { ListNode q = new ListNode(0); //利用快慢指针 q.next = head; ListNode faster = head; ListNode slower = q; while(faster != null && n > 0){ faster = faster.next; n = n -1; } while(faster != null){ faster = faster.next; slower = slower.next; } slower.next = slower.next.next; return q.next; } }

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

    最新回复(0)