Leetcode#19Remove Nth Node From End of List

Given a linked list, remove the nth 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.

問題分析,n的取值可能爲1(刪除最後一個),5(刪除第一個),0(不刪除),6(無效刪除),因此我們添加一個頭nHead,並且使用尺寸爲n的滑動窗口,一邊掃描數據,刪除距離鏈表尾爲n的點

public class Solution {

    public ListNode removeNthFromEnd(ListNode head, int n) {

        ListNode nHead=new ListNode(0);

        nHead.next=head;

        ListNode first=nHead;

        ListNode end=head;

        int i=1;

        while(i<n&&end.next!=null)

        {

           end=end.next;

           i++;

        }

        if(i==n)

        {

            while(end.next!=null)

            {

                end=end.next;

                first=first.next;

            }

            first.next=first.next.next;

        }

        

        return nHead.next;

    }

}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章