Remove Nth Node From End of List

来源:互联网 发布:ios软件安装目录 编辑:程序博客网 时间:2024/04/30 10:16
    public ListNode removeNthFromEnd(ListNode head, int n) {        // Start typing your Java solution below        // DO NOT write main() function        ListNode fast = head;        for(int i = 1; i <= n; i++) {            if(fast == null) return head;            fast = fast.next;        }        if(fast == null) {//delete the head;            ListNode tmp = head;            head = head.next;            tmp.next = null;            return head;        }        ListNode slow = head;        while(fast.next != null) {            fast = fast.next;            slow = slow.next;        }        ListNode tmp = slow.next;        slow.next = slow.next.next;        tmp.next = null;        return head;    }

原创粉丝点击