0019_Remove Nth Node From End of List

来源:互联网 发布:猪哼少 知乎 编辑:程序博客网 时间:2024/05/21 14:53

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

    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.

JAVA

用两个指针直接做,但是要考虑删除第一个节点的情况,时间复杂度

O(N)

可是耗时竟然排在接近垫底的位置。。。

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { val = x; } * } */public class Solution {    public ListNode removeNthFromEnd(ListNode head, int n) {        if(head == null && n == 0){            return head;        }        ListNode delNext = head;        ListNode tail= head;        for(int i = 0;i < n; ++i){            tail = tail.next;        }        while(tail != null && tail.next != null){            delNext = delNext.next;            tail = tail.next;        }        if(delNext == head && tail == null){            head = head.next;        }else{            delNext.next = delNext.next.next;        }        return head;    }}
原创粉丝点击