Remove Nth Node From End of List

来源:互联网 发布:新旧系统数据迁移方案 编辑:程序博客网 时间:2024/06/05 22:56
/** * 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) {        if(head == null) {            return null;        }        ListNode slow = head, fast = head;        for(int i = 0; i < n; i++) {            fast = fast.next;        }        // n == list size        if(fast == null) {            return head.next;        }        while(fast.next != null) {            fast = fast.next;            slow = slow.next;        }        slow.next = slow.next.next;        return head;    }}


Time: O(n)

Space: O(1)

0 0